How to compile template loaded from external api in Vue
After many hours, I managed to pass some properties to the component to be compiled.
In the HTML body:
<!-- some where in the HTML body -->
<div id="vCard2">
<component :is="compiled"></component>
</div>
<script>
var vmCard2 = new Vue({
el: '#vCard2',
data: {
compiled: null,
status: ''
},
methods: {
show: function () {
// macro is some dynamic string content or html template that contains mustache
var macro = this.status == 'some_switch' ? '...{{payment.status}}...' : '...{{refund.status}}...';
Vue.component('cp-macro', {
data: function () {
return {
payment: vmCard1.payment,
refund: vmCard1.refund
}
},
template: '<span>'+macro+'</span>'
})
this.compiled = Vue.compile('<cp-macro></cp-macro>');
},
hide: function () {
this.compiled = null; // must remove for the next macro to show
}
}
})
</script>
There is a compile function available in Vue that compiles templates to render functions. Using the compiled functions requires a little more detail than you have provided (if you needed to use the returned template with data, for example), but here is one example.
console.clear()
Vue.component("my-component",{
template: `<h1>My Component</h1>`
})
const template = `
<div>
<h1>Add client</h1>
<div>My static content</div>
<my-component></my-component>
</div>
`
new Vue({
el: "#app",
data:{
compiled: null
},
mounted(){
setTimeout(() => {
this.compiled = Vue.compile(template)
}, 500)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
<div id="app">
<component :is="compiled"></component>
</div>
Note that in the example, I wrapped your example template in a div
tag. Vue requires that there is on a single root element for a Vue or component.