0中同级组件之间的通信

0中同级组件之间的通信

本文介绍了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):

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

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

[链接到讨论]

并且:

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

    08-20 10:47