Search code examples
vue.jsvuejs2vue-component

Render v-html as VUE components


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

The VUE container that previews the component is this:

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

The content of code is raw HTML, let's say 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>

Note that both <STEP> and <INSTRUCTION> are valid components:

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

What is the easiest way to force <quickpreview> to show HTML content as the VUE components defined above?


Solution

  • 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" />'
    })
    

    Example on JSFiddle

    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