Vue Compile when inserting into the DOM

Asked

Viewed 86 times

0

I need to insert a compiled element into DOM, but it will be inserted in a random place, not in a predefined place as this 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 me because they also need 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 I didn’t find the compiled result in these objects, it seems to me that he is recorded in a promisse, which is triggered when the element is predefined in the FOD.

Finally, it is possible to insert elements compiled in the DOM with vue 2?

1 answer

0


I managed to solve

First of all, I believe which components added dynamically can not communicate to the internal methods of the instance Vue but rather with their own methods, finally, to add a component to the DOM used $mount...

let comp = Vue.component('comp', {
  template: '<div @click.stop="alert">Hello!</div>',
  methods : {
  	alert () {
    	alert('hello');
    }
  }
})

new Vue({
	el: '#app',
  methods : {
    replace () {
    	new comp().$mount('#test');
    }
  },
  components : {
  	comp
  }
})
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<body>

  <div id="app" @click.stop="replace">
  
    <div id="test">
    test
    </div>

  </div>

</body>

Reference Andrejs Abrickis Medium

Browser other questions tagged

You are not signed in. Login or sign up in order to post.