Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
80
rated 0 times [  84] [ 4]  / answers: 1 / hits: 20981  / 8 Years ago, mon, june 27, 2016, 12:00:00

I am trying to create a global event bus so that two sibling components can communicate with each other. I have searched around; however, I cannot find any examples of how to implement one. This is what I have so far:



var bus = new Vue();

Vue.component('Increment', {
template: #inc,
data: function() {
return ({count: 0})
},
methods: {
increment: function(){
var increment = this.count++
bus.$emit('inc', increment)
}
}
})

Vue.component('Display', {
template: #display,
data: function(){
return({count: 0})
},
created: function(){
bus.$on('inc', function(num){
alert(num)
this.count = num;
});
}
})


vm = new Vue({
el: #example,
})


I created my templates like so: http://codepen.io/p-adams/pen/PzpZBg



I'd like the Increment component to communicate the count to the Display component. I am not sure what I am doing wrong in bus.$on().


More From » vue.js

 Answers
6

The problem is that within your bus.$on function, this refers to the bus. You just need to bind the current Vue instance to that function using .bind():



bus.$on('inc', function(num){
alert(num)
this.count = num;
}.bind(this));


You should also check out https://github.com/vuejs/vuex if you want to manage global application states.



EDIT: Since this page seems to get a lot of clicks I want to edit and add another method, per ChristopheMarois in the comments:



EDIT: In effort to make this answer a little clearer, and so future readers don't need to read comments here's what's happening:



Using a fat arrow like below binds the lexical scope of 'this' to the component instead of to the event bus.



bus.$on('inc', (num) => {
alert(num);
this.count = num;
});


Or removing the alert:



bus.$on('inc', (num) => this.count = num);

[#61610] Saturday, June 25, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alenaautump

Total Points: 87
Total Questions: 109
Total Answers: 109

Location: Libya
Member since Mon, Dec 7, 2020
4 Years ago
;