Skip to content
Advertisement

Vue compile when inserting in DOM

I need to insert a compiled element into the DOM, however it will be inserted into a random place, not in a pre-defined location as is documentation…

var res = Vue.compile('<div><span>{{ msg }}</span></div>')
new Vue({
  data: {
    msg: 'hello'
  },
  render: res.render,
  staticRenderFns: res.staticRenderFns
})

All approaches with V-for, V-if/show will not serve as they also require predefined elements.

I tried something like this…

document.getElementById('elPai').insertAdjacentHTML('beforeend', Vue.compile('<div><span>{{ msg }}</span></div>'));

It returns an object containing ‘ render ‘ and ‘ StaticRenderFns ‘, but did not find the result compiled on these objects, it seems to me that it is recorded in a ‘ Promisse ‘, which is triggered when the element is predefined in ‘ DOM ‘.

Finally, there is how to insert elements compiled into DOM with ‘ Vue 2 ‘?

Advertisement

Answer

Try this

var MyComponent = Vue.extend({
  template: '<div>Hello!</div>'
})

new MyComponent().$mount('#app')

Example from: https://v2.vuejs.org/v2/api/#vm-mount

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement