javascript - In vue, how do I check if any parent component has subscribed for an event which child is emitting? - Stack Overflo

I have a ponent which is sometimes being used as a child of a parent and sometimes it does not have any

I have a ponent which is sometimes being used as a child of a parent and sometimes it does not have any parent.

This ponent emits a particular event which either being caught by the parent ( if subscribed) or I would like to handle it by this ponent itself.

So at run time, How do I programmatically check

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

I have a ponent which is sometimes being used as a child of a parent and sometimes it does not have any parent.

This ponent emits a particular event which either being caught by the parent ( if subscribed) or I would like to handle it by this ponent itself.

So at run time, How do I programmatically check

if (someone is listening to the event){
    let them catch and handle it
}else {
    let's handle it by our own
}
Share Improve this question asked May 27, 2019 at 12:06 Amit GoreAmit Gore 4514 silver badges13 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

This allows you to check listeners passed to a ponent:

this.$listeners;

It returns the parent scope event listeners. See the doc here.

In particular for your use-case:

// 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
}

You can pass a boolean prop from your parent.

In Parent Component :

<Child :isParent='true'></Child>

In Child Component :

props : {
  isParent : Boolean
},

methods : {
  actionEvent : function(){
    if(this.isParent){
      // Emit event
    }
    else{
      // Take care over here.
    }
  }
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744662541a4586548.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信