Vue compile when inserting in DOM

Viewed 2823

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

2 Answers

You almost got it right, but for mounting it, you use .$mount() (like in @Wszerad's answer):

console.clear();

var res = Vue.compile('<div><span>{{ msg }}</span></div>');

console.log(res);

var vm = new Vue({
  data: {
    msg: 'hello'
  },
  render: res.render,
  staticRenderFns: res.staticRenderFns
});

vm.$mount('#app')
<script src="https://unpkg.com/vue@2.5.5/dist/vue.js"></script>
<body>
  <div id="app"></div>
</body>

Related