将 v-html 渲染为 VUE 组件 [英] Render v-html as VUE components

查看:164
本文介绍了将 v-html 渲染为 VUE 组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to create a VUE component preview (similar to JSFiddle/CodePen), in VUE.

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

The VUE container that needs to show the end-user how a component looks like:

<quickpreview v-html="code"></quickpreview>

code 的内容是原始 HTML,如下所示:

The content of code is raw HTML, like this:

<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>

都是有效的组件:

Both <STEP> and <INSTRUCTION> are valid components:

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

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

Which is the easiest way to force <quickpreview> to show html content as the VUE components that I have defined?

推荐答案

您可以使用 Vue.compile() 将一个动态模板编译成Vue组件并使用render() 中渲染结果.

You can use Vue.compile() to compile a dynamic template into a Vue component and use render() in <quick-preview /> to render the result.

// 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,因为瘦身, 仅运行时 构建不包含编译器!可以在此处

Note: You need a full build of Vue.js to use template at runtime because the slimmed down, runtime-only build doesn't contain the compiler! More info can be found here

这篇关于将 v-html 渲染为 VUE 组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆