Reputation: 14361
I have a dynamically instantiated vue component which should communicate with the root vue instance via an event. The component (a dialog form) issues the event with this.$root.$emit()
and the root listens with this.$root.$on()
and no event arrives. When I debug I see two different instances of this.$root
which are not the same:
What am I doing wrong?
https://codepen.io/anon/pen/XGoPmj
// Define component
const StepForm = Vue.extend({
methods: {
save() {
console.log("sending event to ", this.$root)
this.$root.$emit('stepSave');
}
}
});
// Dynamically create component
let frm = document.createElement('div');
frm.setAttribute('id', 'myForm');
document.getElementById('root').appendChild(frm);
let dialog = new StepForm().$mount('#myForm');;
new Vue({
el: '#root',
mounted() {
this.$root.$on('stepSave', ()=>{
// This never arrives!
console.log("Got the event!")
});
console.log('I am the root', this.$root)
}
});
function doIt() {
dialog.save()
}
UPDATE: SOLUTION: TLDR: Basically you have to create your component after your root vue instance and pass that instance to your constructor.
Upvotes: 1
Views: 101
Reputation: 29167
You need to specify the parent when the component is created. Otherwise, the $root
will be equal to the component itself:
dialog = new StepForm({
parent: root
}).$mount('#myForm');
[ https://jsfiddle.net/stdob__/qcusdr67/ ]
Upvotes: 3