I'm trying to create a VUE component preview (similar to JSFiddle/CodePen), in VUE.
The VUE container that needs to show the end-user how a component looks like:
<quickpreview v-html="code"></quickpreview>
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
}
Which is the easiest way to force <quickpreview>
to show html content as the VUE components that I have defined?
Vue has a built-in v-html directive by using that we can render a html string. The v-html directive is a vue version of browser innerHTML property. This above code will render an h1 element with red color inside the div.
For example, the following render function is a perfectly valid way of rendering 20 identical paragraphs: Wherever something can be easily accomplished in plain JavaScript, Vue render functions do not provide a proprietary alternative.
More info can be found here Thanks, but with correction. As Vue.compile can contain only exactly one root element, it would be more appropriate to render (h) { const div = document.createElement ('div'); div.innerHTML = this.code; return h (Vue.compile (div.outerHTML)); }
The v-html directive is a vue version of browser innerHTML property. This above code will render an h1 element with red color inside the div. Note: By using the v-html directive you are vulnerable to cross-site scripting attacks (XSS), to prevent from it sanitize your html before passing it to v-html directive.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With