Vue.js dynamic add and remove

I'm learning Vue.js for my game and I was wondering if there is a way to dynamically add and remove components in Vue.js ? Here's my current code

var vue = new Vue({
    el: "#fui",
    template: ``
})

const HelloCtor = Vue.extend({
  props: ['text'],
  template: '<div class="hello">{{ text }}</div>',
});

const vm = new HelloCtor({
  data: {
    text: 'HI :)'
  }
});

/*
How can I do something like this?

vue.add(vm);
vue.remove(vm);

*/

The code basically speaks for himself

So, is it possible (and how?) to dynamically add and remove Vue.js components to a Vue?

1 answer

  • answered 2017-06-17 18:22 MarkM

    You need a place to put vm in the template. Then you can $mount the component manually to an element with vm.$mount('el'). You can also delete the element with vm.$destroy(true). Destroy won't delete the element from the DOM. You'll need to do that manually with something like (vm.$el).remove()

    I'm not 100% this is what you're looking for, and when you find yourself manually calling $destroy() you are probably not doing things right…but it does let you take control of the creating and destruction of components.

    Something like this will let you create then destroy your component (note in this case once you destroy vm it's gone):

    <div id="fui">
        <button @click="make">Make</button>
        <button  @click="bye">destroy</button>
        <div id="mountme"></div>
    </div>
    
    <script>
    
        const HelloCtor = Vue.extend({
            props: ['text'],
            template: '<div class="hello">This has been {{ text }}</div>',
    
        })
    
        const vm = new HelloCtor ({
            data: {
                text: "Mounted"
            }
        })
    
        var vue = new Vue({
            el: "#fui",
            template: ``,
            methods: {
                make: () => {
                    vm.$mount('#mountme')
                },
                bye: () => {
                    vm.$destroy(true); 
                    (vm.$el).remove();}
                }
    
            })
    
    
    </script>