我正在尝试创建一个全局事件总线,以便两个同级组件可以相互通信。我四处寻找;但是,我找不到任何有关如何实现的示例。这是我目前所拥有的:
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",
})
我这样创建了模板:http://codepen.io/p-adams/pen/PzpZBg
我希望 Increment
组件将计数传达给 Display
组件。我不确定我在 bus.$on()
中做错了什么。
最佳答案
问题是在您的 bus.$on
函数中,this
指的是总线。您只需要使用 .bind()
将当前 Vue 实例绑定(bind)到该函数:
bus.$on('inc', function(num){
alert(num)
this.count = num;
}.bind(this));
您还应该查看 https://github.com/vuejs/vuex如果您想管理全局应用程序状态。
编辑:由于此页面似乎获得了很多点击,我想根据评论中的 ChristopheMarois 进行编辑并添加另一种方法:
编辑:为了让这个答案更清楚一点,所以 future 的读者不需要阅读这里发生的评论:
使用像下面这样的粗箭头将“this”的词法范围绑定(bind)到组件而不是事件总线。
bus.$on('inc', (num) => {
alert(num);
this.count = num;
});
或删除警报:
bus.$on('inc', (num) => this.count = num);
关于javascript - Vue.js 全局事件总线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38064054/