Vue.js global event bus

后端 未结 4 1643
被撕碎了的回忆
被撕碎了的回忆 2020-12-31 04:40

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 t

4条回答
  •  一个人的身影
    2020-12-31 05:31

    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);
    

提交回复
热议问题