将 v-html 渲染为 VUE 组件

ade*_*ago 5 vue.js vue-component vuejs2

我正在尝试在 VUE 中创建一个 VUE 组件预览(类似于 JSFiddle/CodePen)。

需要向最终用户展示组件外观的 VUE 容器:

<quickpreview v-html="code"></quickpreview>
Run Code Online (Sandbox Code Playgroud)

的内容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>
Run Code Online (Sandbox Code Playgroud)

这两个<STEP><INSTRUCTION>有效成分:

components: {
  'step': Step // Step.vue exists
  'instruction': Instruction // Instruction.vue exists
}
Run Code Online (Sandbox Code Playgroud)

强制<quickpreview>将 html 内容显示为我定义的 VUE 组件的最简单方法是什么?

riy*_*ali 6

您可以使用Vue.compile()动态模板编译为 aVue component并使用render()in<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" />'
})
Run Code Online (Sandbox Code Playgroud)

JSFiddle上的示例

注意:您需要一个完整的构建Vue.js到使用template在运行时由于精简下来只有运行时生成不包含编译器!更多信息可以在这里找到