我正在尝试创建一个全局事件总线,以便两个同级组件可以相互通信。我四处寻找;但是,我找不到任何有关如何实施的示例。这是我到目前为止所拥有的:
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()
做错了什么。
原文由 Mahmud Adam 发布,翻译遵循 CC BY-SA 4.0 许可协议
问题是在你的
bus.$on
函数中,this
指的是总线。您只需要使用.bind()
将当前 Vue 实例绑定到该函数:如果你想管理全局应用程序状态,你还应该查看 https://github.com/vuejs/vuex 。
编辑:由于此页面似乎获得了很多点击,我想根据评论中的 ChristopheMarois 编辑并添加另一种方法:
编辑:为了让这个答案更清楚一点,所以未来的读者不需要阅读这里发生的事情的评论:
使用像下面这样的粗箭头将“this”的词法范围绑定到组件而不是事件总线。
或删除警报: