vue.js - 将 v-html 渲染为 VUE 组件

标签 vue.js vuejs2 vue-component

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

相关文章:

vue.js - Vue.use 和使用 VueRouter 导入构造函数之间的区别

vue.js - axios 无法设置数据

javascript - 如何在Vue js中做一个无限滚动,动态渲染一个列表(只可见)

javascript - Vue.Js,如何在 v-for 中使用动态颜色和类

javascript - 无法使用 VueRouter 渲染子组件

laravel-5 - 如何切换 VueJs 组件的可见性?

vue.js - 如何设置全局导入的Vue组件具有预设属性?

javascript - vuejs 2 上一个和下一个过渡

javascript - Vue : Child string prop wont render

vue.js - 为什么 v-model 会改变 Vuex 状态而不是组件的本地数据?