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

前端 未结 2 761
鱼传尺愫
鱼传尺愫 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:05

    One way to instantiate Vue components in runtime-generated HTML is:

    var ComponentClass = Vue.extend({
        template: '...',
    });
    var instance = new ComponentClass({
        propsData: { name: value },
    });
    instance.$mount('#uid'); // HTML contains <... id="uid">
    ...
    instance.$destroy(); // if HTML containing id="uid" is dropped
    

    More here (I am not affiliated with this site)
    https://css-tricks.com/creating-vue-js-component-instances-programmatically/

    0 讨论(0)
  • 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 = $('<div is="simple-counter" inline-template> ..rest of template here.. <div>').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/

    0 讨论(0)
提交回复
热议问题