VueJs 2.0中兄弟组件之间的通信 [英] Communication between sibling components in VueJs 2.0

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

问题描述

在vuejs 2.0 model.sync 已弃用



那么,在 vuejs 2.0



当我抓住这个想法在Vue 2.0中,通过使用商店或事件总线进行兄弟通信



根据 evan


值得一提的是在组件之间传递数据是
一般是个坏主意,因为最后数据流变成
无法检查并且很难调试。



如果一个数据需要由多个组件共享,则更喜欢
全球商店 Vuex


[链接到讨论]



并且:


.once .sync 已弃用。道具现在总是单向下降。要
在父作用域中产生副作用,组件需要
显式 emit 一个事件,而不是依赖于隐式绑定。


(所以,他建议是使用 $ emit $



我担心因为:




  • 每个商店事件具有全局可见性(如果我错了,请纠正我);

  • 创建新商店要做得很多对于每次次要的沟通;



我想要的是范围以某种方式事件存储兄弟姐妹组件的可见性。或许我没有理解这个想法。



那么,如何以正确的方式沟通?

解决方案

使用Vue 2.0,我正在使用eventHub机制,如文档


  1. 定义集中事件中心。

      const eventHub = new Vue()//单个事件中心

    //使用全局mixin $ b $分发到组件b Vue.mixin({
    data:function(){
    return {
    eventHub:eventHub
    }
    }
    })


  2. 现在,在您的组件中,您可以使用



    $ b <$发出事件p $ p> this.eventHub。$ emit('update',data)


  3. 听你说

      this.eventHub。$ on('update',data => { 
    //做你的事情
    })


更新
使用 $ root 作为活动中心(如 @alex 所述)。

  ///发射器
这个。$ root。$ emit(...)

//听众
这个。$ root。$ on(...)


In vuejs 2.0 model.sync will be deprecated.

So, what is a proper way to communicate between sibling components in vuejs 2.0?

As I catch the idea in Vue 2.0 is to have sibling communication by using a store or an event bus.

According to evan:

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.

[Link to discussion]

And:

.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.

(So, he suggest is to use $emit and $on)

I'm worried because of:

  • Each store and event has a global visibility (correct me if I'm wrong);
  • It's to much to create a new store for each minor communication;

What I want is to scope somehow events or stores visibility for siblings components. Or perhaps I didn't catch the idea.

So, how communicate in a right way?

解决方案

With Vue 2.0, I'm using the eventHub mechanism as demonstrated in the documentation.

  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
            }
        }
    })
    

  2. Now in your component you can emit events with

    this.eventHub.$emit('update', data)
    

  3. And to listen you do

    this.eventHub.$on('update', data => {
    // do your thing
    })
    

Update There is nice trick to use $root as event hub (as described by @alex).

    /// on emitter
    this.$root.$emit(...)

    // on listener
    this.$root.$on(...)

这篇关于VueJs 2.0中兄弟组件之间的通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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