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

查看:22
本文介绍了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.

如果一条数据需要被多个组件共享,优先选择全球商店Vuex.

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

[讨论链接]

还有:

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

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

  • 更新

    请参阅亚历克斯的回答,它描述了一个更简单的解决方案.

    Please see the answer by alex, which describes a simpler solution.

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

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