Vue Js Non Child Parent Communication With Event Bus Does Not Work
In vue js document, there is a way to communicate between non parent child components.vue document. But when I tried this method, it did not work. Below is my code. Is there any he
Solution 1:
This is a scoping issue. Adjust your mounted
hook as follows:
mounted() {
const self = this; // save pointer to current 'this'
bus.$on('idSelected', function(value) {
console.log('??? app10 click event value: ', value);
self.id = value; // use 'self' hereconsole.log('??? this.id', this.id);
});
}
Otherwise you loose a reference to current 'this', because it equals to 'bus' in your event listener. Try to console.log(this === bus)
inside your listener ( == true).
Solution 2:
The value of this
is changing in your code inside your anonymous function. Use arrow function instead to keep the context of your vue instance.
var bus = newVue();
Vue.component('component3', {
template: `
<div @click='change'>
{{id}}
</div>
`,
props: ['id'],
methods: {
change() {
console.log('??? component3 emit');
bus.$emit('idSelected', 3);
}
},
mounted() {
}
});
Vue.component('component4', {
template: `
<div>
{{id}}
</div>
`,
props: ['id'],
});
var app10 = newVue({
el: '#app10',
data: function() {
return {
id: '?'
}
},
mounted() {
bus.$on('idSelected', (value) => {
console.log('??? app10 click event value: ', value);
this.id = value;
console.log('??? this.id', this.id);
});
}
});
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script><html><body><divid="app10"><component3:id="id"></component3><component4:id="id"></component4></div></body></html>
Post a Comment for "Vue Js Non Child Parent Communication With Event Bus Does Not Work"