【问题标题】:In vue, how do I check if any parent component has subscribed for an event which child is emitting?在 vue 中,如何检查是否有父组件订阅了子组件发出的事件?
【发布时间】:2019-05-27 12:06:58
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component


    【解决方案1】:

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

    this.$listeners;
    

    它返回父范围事件监听器。见the doc here

    特别是针对您的用例:

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

    【讨论】:

    • '这似乎是一个有问题的设计' 我希望为我的一个组件这样做。子组件显示一个金额字段,父母对此字段的更改做出反应。现在我们想让这个相同的组件不显示加号和减号按钮,如果父级通过不订阅事件以只读方式使用该组件...对我来说听起来不错的设计。
    • 我同意。我想那天我的想象力不够用了 :) 我会删除那条评论。
    【解决方案2】:

    你可以从你的父母那里传递一个布尔属性。

    在父组件中:

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

    在子组件中:

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

    【讨论】:

    • 有道理。但是我们可以在不污染道具空间的情况下做到这一点吗? @vaibhav
    • 其他选项是你可以参考伯尼的回答,理论上应该可以。
    猜你喜欢
    • 2021-07-26
    • 2014-09-25
    • 2015-04-18
    • 1970-01-01
    • 2021-07-18
    • 2011-04-05
    • 2020-04-19
    • 2019-09-24
    • 2021-09-17
    相关资源
    最近更新 更多