如何使用 Vue.js 2 中的事件总线通过自定义事件传递数据 [英] How to pass data with custom events using an event bus in 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屋!