最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论