问题描述
我已经阅读了 vue.js 事件部分的事件,但它似乎只给出了如何使用 html 中的 vm.$on 处理程序来侦听事件的示例.在这与 2.0 的新变化之间,我不确定如何简单地从 child -> parent 传输事件.
I've been through the vue.js events section on events but it seems to only give examples of how to listen to events using the vm.$on handler within html. Between that and the new changes for 2.0 I'm unsure how to simply transmit a event from child -> parent.
我需要传输一个事件,因为在父母收到后我想将它广播给另一个孩子.
I need to transmit an event because after parent receiving i want to broadcast it to another child.
我使用的是单页组件,这是我的设置:
I'm using single page components, this is my setup:
// parent
export default {
mounted: function () {
this.$on('myEvent', function (msg) {
console.log('caught in parent', msg)
});
},
components: {
'child': child,
},
}
// child
this.$emit('myEvent', true)
请问如何在父虚拟机上接收此事件?注意,我不想在 html 中使用 $on.我希望 vm 中的事件接收逻辑应该在那里.
How can I receive this event on the parent vm please? Note, I don't want to use $on in the html. I want the event receiving logic in the vm where it should be.
谢谢,
推荐答案
Vues
关于 $emit
的文档不是很全面,但是有一些方法可以做到这个.首先,如果你想使用 this.$on()
,你必须在你想要发送消息的 vue 模型上 $emit
,所以如果你从一个您可以使用以下方法发送给直接父级的组件:
Vues
documentation on $emit
is not very comprehensive, however, there are a few ways to do this. Firstly you have to $emit
on the vue model you want to send the message to if you want to use this.$on()
, so if you are sending from a component you can emit to the direct parent using:
this.$parent.$emit('myEvent',true);
但是,如果您有很长的父链,这可能会成为问题,因为您必须在子链上$emit
,因此在这种情况下,您可以使用 Vue 实例作为总线:
However, this can become problematic if you have a long chain of parents because you have to $emit
up the child chain, so in that case you can use a Vue instance as a bus:
// In the root as a global variable so all components have access
var bus = new Vue({});
或者如果您使用的是单文件组件.
Or if you are using single file components.
window.bus = new Vue({});
然后在接收器中:
bus.$on('myEvent',() => {
// Do stuff
});
在发射器中:
bus.$emit('myEvent',true);
最后,如果你发现 app
对于一个简单的总线来说太复杂了,那么你可以使用 vuex
:
Finally, if you find you app
getting too complex for a simple bus then you can use vuex
:
https://vuex.vuejs.org/en/index.html
这篇关于使用 vm.$on 监听 vue.js 2.0 中 child 发出的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!