Vue.js mount component after DOM tree mutation to add a vue component

前端 未结 2 759
鱼传尺愫
鱼传尺愫 2021-02-10 18:34

I have a use case (below) where I need to mount (if thats the correct term) a Vue.js component template that was inserted into the DOM via jQuery, I can setup a Mut

2条回答
  •  后悔当初
    2021-02-10 19:12

    Thanks to @liam I was able to find an appropriate solution to my problem

    After mutating the DOM with the HTML template, keep a reference to that template's parent element

    for example:

    var $template = $('
    ..rest of template here..
    ').appendTo('#app') // app is the Vue instance el or a child of it

    Now you can create a new instance of your component and add $template to it as the el property

    if my component was:

    var simpleCounterComponent = Vue.component('simple-counter', {
      data: function() {
        return {
          counter: 0,
          style: {
            color: 'red',
            width: '200px'
          }
        }
      },
      methods: {
        add: function() {
          this.counter = this.counter + 1;
          this.style.color = this.style.color == 'red' ? 'green' : 'red';
        }
      }
    })
    

    I can do:

    var instance = new simpleCounterComponent({
      el: $template.get(0) // getting an HTML element not a jQuery object
    });
    

    And this way, that newly added template has become a Vue component

    Take a look at this fiddle for working example based on the question:

    https://jsfiddle.net/947ojvnw/11/

提交回复
热议问题