动态渲染 vue 模板 [英] dynamically render vue template
问题描述
我将 vue 模板数据作为字符串.例如,String s = "
"
现在我想在我已经定义的 vue 组件中渲染.
<div>在这里我需要放置字符串
</模板><脚本>导出默认{name: 'HelloWorld',数据: {我的数据:铁人"},}
现在我想要输出为 IRONMAN
我怎样才能做到这一点?请帮忙.谢谢
您可以使用单个文件组件来执行此操作 - 我有一个名为 Dynamic.vue
的组件,它接受一个 HTML 字符串 - 我使用这允许用户生成他们自己的模板并且所有绑定都正确匹配,例如:
如果你这样称呼它:
this.htmlData = '<div>Hello - {{{someVar}}</div>'....<my-dynamic-component :template-html="htmlData"/>`
你会看到输出
<块引用>你好测试
然后您将省略 SFC 中的 部分.
注意:为了让这个工作,你还必须在你的项目中包含 Vue 编译器(因为它负责将 SFC 编译成 Vue 用来显示数据的渲染函数).
此链接:https://vuejs.org/v2/guide/installation.html#CLI 可以提供有关包含 Vue 编译器的更多信息.
I have vue template data as string. For example,
String s = "<div>{{myData}}</div>"
And now I want to render in my already defined vue component.
<template>
<div>
HERE I NEED TO PLACE THE STRING
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data: {
myData: "IRONMAN"
},
}
</script>
Now I want the output as IRONMAN
How can i achieve this? Pleas help. Thanks
You can have a single file component and do this - I have one called Dynamic.vue
which accepts a HTML string - I use this to allow the users to generate their own templates and the bindings all match up properly, something like:
<script>
export default {
data () {
return {
someVar: 'Test'
}
},
props: {
templateHtml: {
templateHtml: true,
type: String
}
},
created () {
this.$options.template = this.templateHtml
}
}
</script>
If you were to call it like:
this.htmlData = '<div>Hello - {{{someVar}}</div>'
....
<my-dynamic-component :template-html="htmlData" />`
You would see the output
Hello Test
You would then omit the <template>
part in the SFC.
Note: In order for this to work, you must also have the Vue Compiler included in your project (as this handles compiling the SFC into render functions which Vue uses to display data).
This link: https://vuejs.org/v2/guide/installation.html#CLI can give more information about including the Vue Compiler.
这篇关于动态渲染 vue 模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!