在 vue 中,如何检查父组件是否订阅了子组件发出的事件?

Ami*_*ore 4 javascript vue.js vue-component vuejs2

我有一个组件,有时被用作父组件的子组件,有时它没有任何父组件。

该组件发出一个特定的事件,该事件要么被父级捕获(如果订阅),要么我想由该组件本身处理它。

那么在运行时,我如何以编程方式检查

if (someone is listening to the event){
    let them catch and handle it
}else {
    let's handle it by our own
}
Run Code Online (Sandbox Code Playgroud)

ber*_*nie 7

这允许您检查传递给组件的侦听器:

this.$listeners;
Run Code Online (Sandbox Code Playgroud)

它返回父范围事件侦听器。请参阅此处的文档

特别是对于您的用例:

// To check whether the "myEvent" event is listened to
if (this.$listeners.myEvent){
  // let them catch and handle it
} else {
  // let's handle it by our own
}
Run Code Online (Sandbox Code Playgroud)