why dynamically mounted vuejs content is not child

2019-07-11 12:17发布

I load some html containing customized component, and mount that content to a fixed node in parent component. Unfortunately, i found there is no parent-child relationship between them, so the events dispatched by dynamically inserted component can not be received by root vue. I have created one fiddle, any help or proposal is appreciated!. http://jsfiddle.net/matiascx/7Ljygv81/1/

<div id="app">
    <button v-on="click: addNewElement()">Add custom Element</button> 
    <br />
    <div id="dynamicloaded"></div>
</div>

JS:

new Vue({
    el: '#app',
    data: {
        sampleElement: '<div class="dynamic-child"><button v-on="click: test()">Test</button></div>'

    },
    methods:{
        addNewElement: function(){



           var vmtemp = Vue.extend({
                            template: this.sampleElement,
                            methods: {
                             test: function(){
                               alert("comes from dynamically loaded content");
                               this.$dispatch('child-msg','this comes from ajax loaded component');
                             }
                            }
                        });
           new vmtemp().$mount(document.getElementById('dynamicloaded'));
        },
        test: function(){
           alert('Test');
        },
        events: {
         'child-msg': function(msg){
            console.log('message received'+msg);
         }
        }
    }
});

2条回答
不美不萌又怎样
2楼-- · 2019-07-11 12:45

Normally when you create dynamically a Vue component is not child of any particular instance. You can set the parent explicitly within the options

var _this = this
var child = new vmtemp({parent:_this}).$mount(document.getElementById('dynamicloaded'))

Inside your addNewElement function.

Let me know if it works for you.

查看更多
放荡不羁爱自由
3楼-- · 2019-07-11 12:48

thanks to the vuejs creator's help, i have tried async component approach, it really works and right parent-child relationship setup when after dynamic content rendered into dom. https://github.com/vuejs/vue/issues/3255#issuecomment-231686976

查看更多
登录 后发表回答