如何监听VueJS中的所有自定义事件?

2023-11-26

在我的 VueJS 应用程序中,我有一个 Vue 实例,我将其用作事件总线,用于在组件之间发送数据。

就是这样:

import Vue from 'vue';
export const EventBus = new Vue();

然后在我的组件中导入 EventBus 并使用EventBus.$emit() and EventBus.$on().

这种方法的解释如下:https://alligator.io/vuejs/global-event-bus/

我想要做的是监听通过 EventBus 发送的任何事件。如果我可以将一个侦听器绑定到所有事件,我可以使用它进行日志记录或将数据输入到我的开发环境的某个系统中,该系统会在进入 eventBus 时向我显示所有数据,这将非常有用。

有没有任何类型的vm.$listenToEverything()我失踪了或者有什么方法可以让这项工作成功?


如果您处于 ES6 环境中,您可以采用以下任一方法。我通过评论来解释。

通过继承覆盖

'use strict'

import Vue from 'vue'

export class EventBus extends Vue {
  // Register a custom callback as meddler that gets called upon each event emission.
  // It can be bound to $on as well. 
  $meddle (callback) {
    this.meddler = callback
  }

  // Override Vue's $emit to call the custom meddler callback upon each event emission.
  $emit (event, ...args) {
    if (this.meddler && typeof this.meddler.call === 'function') {
      this.meddler(event, ...args)
    }

    return super.$emit(event, ...args)
  }

  // We can also override $on() to listen to callbacks being registered.
}

export default new EventBus()

通过劫持进行覆盖

或者使用“劫持”工厂类,以防您不希望 Vue 事件总线被包装。逻辑基本相同,但是,在这种方法中我们hijack,或者换句话说,猴子补丁方法而不是直接覆盖它们。

'use strict'

import Vue from 'vue'

class EventBusFactory {
  static create () {
    return this.hijack(new Vue())
  }

  static hijack (bus) {
    bus.$meddle = callback => {
      bus.meddler = callback
    }

    const orig$emit = bus.$emit
    bus.$emit = (event, ...args) => {
      if (bus.meddler && typeof bus.meddler.call === 'function') {
        bus.meddler(event, ...args)
      }

      orig$emit.call(bus, event, ...args)
    }

    return bus
  }
}

export default EventBusFactory.create()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何监听VueJS中的所有自定义事件? 的相关文章

随机推荐