问题描述
在Vue.js 2.x中,将弃用 model.sync
.
In Vue.js 2.x, model.sync
will be deprecated.
因此,在 Vue.js 2.x ?
据我了解Vue.js 2.x,兄弟通信的首选方法是使用商店或事件总线.
As I understand Vue.js 2.x, the preferred method for sibling communication is to use a store or an event bus.
根据 Evan (Vue.js的创建者):
According to Evan (creator of Vue.js):
如果一条数据需要由多个组件共享,则首选全球商店或 Vuex .
If a piece of data needs to be shared by multiple components, preferglobal stores or Vuex.
[链接到讨论]
并且:
因此, Evan建议使用$emit()
和$on()
让我担心的是:
- 每个
store
和event
具有全局可见性(如果我输入错了,请纠正我); - 为每次次要沟通创建一个新商店太浪费了;
- Each
store
andevent
has a global visibility (correct me if I'm wrong); - It's too wasteful to create a new store for each minor communication;
我想要的是范围 events
或stores
兄弟姐妹组件的可见性. (或者也许我不理解上面的想法.)
What I want is to some scope events
or stores
visibility for siblings components. (Or perhaps I didn't understand the above idea.)
那么,兄弟姐妹组件之间进行通信的正确方法是什么?
So, what is the correct way to communicate between sibling components?
推荐答案
在Vue.js 2.0中,我正在使用eventHub机制,如所示文档中的.
With Vue.js 2.0, I'm using the eventHub mechanism as demonstrated in the documentation.
-
定义集中式事件中心.
Define centralized event hub.
const eventHub = new Vue() // Single event hub
// Distribute to components using global mixin
Vue.mixin({
data: function () {
return {
eventHub: eventHub
}
}
})
现在您可以在组件中发出事件了
Now in your component you can emit events with
this.eventHub.$emit('update', data)
听你的话
And to listen you do
this.eventHub.$on('update', data => {
// do your thing
})
更新
请参见 Alex的回答,它描述了一种更简单的解决方案.
Please see the answer by alex, which describes a simpler solution.
这篇关于Vue.js 2.0中同级组件之间的通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!