I've created two dynamic components. Now, using events: $emit/$on what I need is to fire the "logThat(someObj)" method of the component-two passing the arguments as you can see in this fiddle:
Vue.component('component-one', {
template: '#template-a',
methods: {
onClick() {
const someObj = {
foo: "foo",
bar: "bar"
}
vm.$emit('selected', someObj)
vm.currentView ='component-two';
}
}
});
//Any hint??
/*vm.$on('selected', (someObj) => {
this.logThat(someObj)
})*/
Vue.component('component-two', {
template: '#template-b',
methods: {
onClick() {
vm.currentView ='component-one';
},
logThat(someObj) {
console.log(someObj);
}
}
});
https://jsfiddle.net/wanxe/yuh71e1o/
If anyone has any suggestions of how to handle this, it will be appreciated :)
Technically, you are supposed to use Non-parent-child communication as given in the docs.
But in your current example, it will not work. Reason: Your components 'one' and 'two' are getting created and destroyed as you move back and forth.
Here is your updated jsFiddle: https://jsfiddle.net/mani04/yuh71e1o/4/. Here are the changes:
Event bus:
Sending event from component-one:
Receiving event in component-two:
If you open the dev console and observe the logs, you will notice that component-two gets created multiple times and the old ones keep listening as they are not fully destroyed.
To overcome this, you need to move away from dynamic components, and have both your
component-one
andcomponent-two
created at the same time on your root template. You may show / hide based on whichever view you desire, usingv-show
(notv-if
which again destroys the component instance). Then you can use the event bus to communicate, as detailed in the Non-parent-child communication docs.