如何使用 Vue.js 2 中的事件总线通过自定义事件传递数据 [英] How to pass data with custom events using an event bus in Vue.js 2

查看:44
本文介绍了如何使用 Vue.js 2 中的事件总线通过自定义事件传递数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Vue.js 2.5.x.

I'm using Vue.js 2.5.x.

在我的玩具项目中,我实现了一个事件总线(类似于 here).事件总线在 Vue 原型中全局注册为 $eventBus.

In my toy project, I've implemented an event bus (similarly to what shown here). The event bus is globally registered in Vue prototype as $eventBus.

然后我创建了一个发出事件的组件,如下所示

Then I created a component that emits an event as follows

this.$eventBus.$emit('actionCompleted')

和另一个注册到该事件以执行其自己的函数(myMethod),如下所示

and another that registers to that event to execute its own function (myMethod), as shown below

export default {
  created: function () {
      this.$eventBus.$on('actionCompleted', this.myMethod)
  },
  methods: {
    myMethod () {
        console.log('myMethod called')
    }
  }
}

到目前为止一切顺利,一切都按预期进行.

So far so good, all works as expected.

问题是:如何将对象传递给我的自定义事件,以便向侦听器发送附加信息?

The question is: how can I pass an object to my custom event so that I can ship additional information to the listeners?

推荐答案

您可以将参数作为第二个参数传递

You can pass your parameter as second argument

this.$eventBus.$emit('actionCompleted', objectParams)

export default {
  created: function () {
      this.$eventBus.$on('actionCompleted', this.myMethod)
  },
  methods: {
    myMethod (objectParams) {
        console.log('myMethod called', objectParams)
    }
  }
}

您可以查看以下教程

这篇关于如何使用 Vue.js 2 中的事件总线通过自定义事件传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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