我正在尝试在 VUE 中创建一个 VUE 组件预览(类似于 JSFiddle/CodePen)。
需要向最终用户显示组件外观的 VUE 容器:
<quickpreview v-html="code"></quickpreview>
code
的内容是原始 HTML,像这样:
<PRE-TASK>
<STEP>
<INSTRUCTION>
<REF-DS>das Teleskopieren ...</REF-DS>.</INSTRUCTION>
</STEP>
<STEP>
<INSTRUCTION>
<REF-DS>Sicherheitsanweisungen ...</REF-DS>.</INSTRUCTION>
</STEP>
<STEP>
<INSTRUCTION>
<REF-DS>Den Teleskopwagen ...</REF-DS>.</INSTRUCTION>
</STEP>
</PRE-TASK>
两者都是 <STEP>
和 <INSTRUCTION>
是有效的组件:
components: {
'step': Step // Step.vue exists
'instruction': Instruction // Instruction.vue exists
}
哪个是强制<quickpreview>
的最简单方法将 Html 内容显示为我定义的 VUE 组件?
最佳答案
您可以使用 Vue.compile()
将动态模板编译成Vue component
并使用 render()
在 <quick-preview />
呈现结果。
// define the available components
Vue.component('steps', {...})
Vue.component('step', {...})
Vue.component('instruction', {...})
// the <quick-preview /> component
Vue.component('quick-preview', {
props: ['code'],
render(h){
// render a 'container' div
return h('div', [
h(Vue.compile(this.code)) // compile and render 'code' string
])
}
})
// then you can use it as
new Vue({
data(){
return {
code: '...'
}
},
template: '<quick-preview :code="code" />'
})
关于 JSFiddle 的示例
注意:您需要完整构建 Vue.js 才能使用template
在运行时因为精简,仅运行时构建不包含编译器!可以找到更多信息 here
关于vue.js - 将 v-html 渲染为 VUE 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51006553/