【问题标题】:Render and Compile String using vue.js使用 vue.js 渲染和编译字符串
【发布时间】:2019-02-10 14:17:10
【问题描述】:

要求所有 html 元素都在 JSON 文件中定义并在模板中使用。

有一个功能 - “markComplete”需要在复选框更改时触发。

代码模板:

<template>
<span v-html="htmlContent"></span>
</template>

<script>
 data(){
        return{
        htmlContent: "<input type='checkbox' v-on:change='markComplete'>"
        }
    }
</script>

上面的代码无法工作,因为onChange 事件不会被挂载,我得到 Uncaught ReferenceError: markComplete is not defined

有什么办法可以做到吗?

【问题讨论】:

  • json文件只是一个字符串,不能包含方法。 makeComplete 必须在 Vue 应用程序的某个地方定义 - 它在哪里?
  • @RichardMatsen 这存在于方法中,我只是没有提到它

标签: vue.js vuejs2 vue-component


【解决方案1】:

您正在尝试使用 v-html 将字符串编译为 Vue 模板。

注意,内容是作为纯 HTML 插入的——它们不会被编译为 Vue 模板

Vue Docs 中了解 v-html。

作为解决方案,您可以阅读this article

您不想使用库?查看以下代码:

先创建一个js文件(最好是RenderString.js):

import Vue from "vue"

Vue.component("RenderString", {
  props: {
    string: {
      required: true,
      type: String
    }
  },
  render(h) {
    const render = {
      template: "<div>" + this.string + "</div>",
      methods: {
        markComplete() {
          console.log('the method called')
        }
      }
    }
    return h(render)
  }
})

然后在你的父组件中:

<template>
  <div><RenderString :string="htmlContent" /></div>
</template>

<script>
import RenderString from "./components/RenderString"

export default {
  name: "App",
  data: () => ({
    htmlContent: "<input type='checkbox' v-on:change='markComplete'>"
  })
}
</script>

注意:我没有运行上面的代码,但我创建了一个类似的工作 CodeSandbox Example

【讨论】:

  • 感谢您的编辑。这工作正常,但应该调用父组件中定义的函数。我试图在更改时发出事件 - this.$emit('ParentFunction');这样做时,既没有错误也没有警告。我哪里错了? CodeSandbox - codesandbox.io/s/k34x9jk02r
  • 很高兴看到它有所帮助。虽然我使用 $emit 更改了沙箱。如果你愿意,你可以看看 -> codesandbox.io/s/x2vry0m8mp
猜你喜欢
  • 1970-01-01
  • 2022-01-26
  • 2015-05-05
  • 2018-04-05
  • 1970-01-01
  • 2018-02-06
  • 2014-06-09
  • 2020-03-14
  • 2012-08-20
相关资源
最近更新 更多