【问题标题】:Render v-html as VUE components将 v-html 渲染为 VUE 组件
【发布时间】:2018-12-03 00:43:48
【问题描述】:

我正在尝试在 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>

&lt;STEP&gt;&lt;INSTRUCTION&gt; 都是有效组件:

components: {
  'step': Step // Step.vue exists
  'instruction': Instruction // Instruction.vue exists
}

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

【问题讨论】:

标签: vue.js vuejs2 vue-component


【解决方案1】:

您可以使用Vue.compile() 将动态模板编译成Vue component,然后在&lt;quick-preview /&gt; 中使用render() 来呈现结果。

// 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,因为精简了 runtime-only 构建不包含编译器!更多信息可以找到here

【讨论】:

  • 当心!这可能会在您的代码中引入 XSS 漏洞!确保您仅以这种方式呈现“受信任”代码,或在呈现之前以某种方式清理 html
  • 谢谢,但有更正。由于Vue.compile 只能包含一个根元素,所以render(h) { const div = document.createElement('div'); div.innerHTML = this.code; return h(Vue.compile(div.outerHTML)); } 更合适
猜你喜欢
  • 2022-10-06
  • 1970-01-01
  • 2019-05-12
  • 2021-09-19
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多