使用 vue.js 渲染和编译字符串 [英] Render and Compile String using vue.js
问题描述
要求在 JSON 文件中定义所有 html 元素并在模板中使用.
有一个函数 - markComplete",需要在更改复选框时触发.
代码模板:
<span v-html="htmlContent"></span></模板><脚本>数据(){返回{htmlContent: ""}}
上面的代码将不起作用,因为 onChange
事件不会被挂载,我得到 Uncaught ReferenceError: markComplete is not defined
有什么办法可以让这个工作吗?
您正在尝试使用 v-html 将该字符串编译为 Vue 模板.
<块引用>请注意,内容是作为纯 HTML 插入的 - 它们不会被编译为 Vue 模板
在 Vue 文档中了解 v-html.
作为解决方案,您可以阅读这篇文章
<块引用>你不想使用图书馆?查看以下代码:
首先创建一个js文件(最好是RenderString.js
):
从vue"导入VueVue.component("RenderString", {道具: {细绳: {要求:真实,类型:字符串}},渲染(h){常量渲染 = {模板:"+ this.string + "</div>",方法: {标记完成(){console.log('调用的方法')}}}返回 h(渲染)}})然后在您的父组件中:
<div><RenderString :string="htmlContent"/></div></模板><脚本>从./components/RenderString"导入RenderString导出默认{名称:应用程序",数据:() =>({htmlContent: ""})}
注意:我没有运行上面的代码,但我创建了一个类似的工作 CodeSandbox 示例
There is a requirement where all html elements are defined in a JSON file and used in the template.
There is a function - "markComplete" which needs to be triggered on change of a checkbox.
Code Template:
<template>
<span v-html="htmlContent"></span>
</template>
<script>
data(){
return{
htmlContent: "<input type='checkbox' v-on:change='markComplete'>"
}
}
</script>
Above code won't work as onChange
event won't be mounted, and I get Uncaught ReferenceError: markComplete is not defined
Is there any way to make this work?
解决方案 You are trying to compile the string as Vue Templates using v-html.
Note that the contents are inserted as plain HTML - they will not be compiled as Vue templates
Read about v-html in Vue Docs.
As solution you can read this article
You don't want to use a library? Checkout the code below:
First create a js file (preferably 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)
}
})
Then in your parent component:
<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>
Note: I didn't run the code above but I created a similar working CodeSandbox Example
这篇关于使用 vue.js 渲染和编译字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文