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);
}
}
}
});
Normally when you create dynamically a Vue component is not child of any particular instance. You can set the parent explicitly within the options
Inside your
addNewElement
function.Let me know if it works for you.
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