Vue.js 2.0中同级组件之间的通信 [英] Communication between sibling components in Vue.js 2.0

查看:159
本文介绍了Vue.js 2.0中同级组件之间的通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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):

还值得一提的是组件之间传递数据".是 通常是个坏主意,因为最终数据流变成了 无法追踪,而且很难调试.

It's also worth mentioning "passing data between components" is generally a bad idea, because in the end the data flow becomes untrackable and very hard to debug.

如果一条数据需要由多个组件共享,则首选 全球商店

If a piece of data needs to be shared by multiple components, prefer global stores or Vuex.

[链接到讨论]

并且:

.once.sync已弃用.现在,道具总是单向下降.到 在父范围内产生副作用,组件需要 明确地emit一个事件,而不是依赖于隐式绑定.

.once and .sync are deprecated. Props are now always one-way down. To produce side effects in the parent scope, a component needs to explicitly emit an event instead of relying on implicit binding.

因此, Evan建议使用$emit()$on()

让我担心的是:

  • 每个storeevent具有全局可见性(如果我输入错了,请纠正我);
  • 为每次次要沟通创建一个新商店太浪费了;
  • Each store and event has a global visibility (correct me if I'm wrong);
  • It's too wasteful to create a new store for each minor communication;

我想要的是范围 eventsstores兄弟姐妹组件的可见性. (或者也许我不理解上面的想法.)

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.

  1. 定义集中式事件中心.

  1. 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中同级组件之间的通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆