我有一个父组件,它有多个子组件
<grid>
<cell></cell>
<cell></cell>
<cell></cell>
</grid>
我的单元格组件发出一个带有有效载荷的事件,表明正在编辑它
this.$emit('editing',cellId)
我知道我可以像这样捕捉事件
<cell @editing="do something"></cell>
或使用 EventBus.$on('editing')
捕获,我也不想使用根监听器 this.$root.$on('editing')
但是因为它是父组件,所以当父组件挂载时,我如何监听'editing'事件
mounted: function(){
this.$on('editing',dosomething)
}
为什么我的父组件挂载后无法添加listen?
最佳答案
您缺少的主要区别在 Custom Events 中进行了描述部分:
In addition, a parent component can listen to the events emitted from a child component using v-on directly in the template where the child component is used.
You cannot use $on to listen to events emitted by children. You must use v-on directly in the template, as in the example below.
这意味着子-父通信是通过指令,使用v-on
(或@edit
)方式完成的.
这里是你的例子
mounted: function(){
this.$on('editing',dosomething)
}
实际上不会工作。在emit documentation据说:
Trigger an event on the current instance.
这意味着在同一个组件中,您实际上可以使用this.$on
,它会起作用。但是如果你想在parent中使用它,那么你应该使用inline指令来绑定(bind)它,否则它不会起作用。
另请记住,emits
仅适用于单个步骤,这意味着父级可以捕获它。如果你需要发射子子 -> 子 -> 父,那么你应该从 subchild
in child
中捕获事件(使用内联绑定(bind)),并再次重新发出它,以便它转到父级。
如果它在父子范围之外,那么您应该使用所谓的全局总线
。基本上它将所有事件缩小到单个实例,该实例 emits
和 listens
所有事件。因此,它们不再是父子关系或任何类型的连接,它们都在同一个实例上,因此您始终可以在您的每个组件中使用它们。
最重要的是——你监听 mounted 的方法是行不通的。希望有所帮助:)
关于javascript - 有没有办法捕获vuejs中多个子组件发出的事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45177171/