Search code examples
vue.jscomponentsmount

Vue JS load dynamic component in element


I have the code below:

let templateName = '#' + className + 'Properties';
const vue2 = {
               template: templateName,
               el: "#app2"
             };
var vm = new Vue(vue2).$mount(); 

Everytime, the variable className will have different value, so that template will be different everytime. Now once I mount the component for the first time, it works, but the same template mounts always even if the className is different.

Please guide


Solution

  • I solved it as below :

                        if (null !== vm) {
                            vm.$destroy();
                            vm.$el.remove()
                            vm = null
                        }
    
                        const vueContainer = document.createElement('div');
                        vueContainer.setAttribute("id", "app9");
                        $("#app2").append(vueContainer);                    
    
                        let templateName = '#' + className + 'Properties';
                        const vue2 = {
                            template: templateName,
                            el: "#app9"
                        };
    
                        vm = (new (Vue.extend(vue2))).$mount(vueContainer)