vue 判断$emit 是否包含指定方法

12/1/2020 vue

不知道小伙伴们有没有遇到过这样的场景:如果父组件传入了方法,使用父组件传入的方法,如果没传,则子组件做其他处理(例如:调用一个子组件的默认方法)。

通常我们使用$emit来调用父组件传进来的方法,不熟悉$emit的小伙伴看这里 (opens new window)

this.$emit('parentEvent', [...args])
1

可以看到$emit只是触发当前实例上的事件,没有相关判断的方法,并且调用一个不存在的方法也不会报错。

那么应该如何实现我们的需求呢? $listeners (opens new window)

// $listeners包含了父作用域中的 (不含 .native 修饰器的) v-on 事件监听器
if (this.$listeners.parentEvent) {
  this.$emit('parentEvent')
} else {
  // 其他处理
}
1
2
3
4
5
6
Last Updated: 9/22/2023, 6:04:11 AM