如何在VueJS中监听所有自定义事件? [英] How to listen to all custom events in VueJS?

查看:432
本文介绍了如何在VueJS中监听所有自定义事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的VueJS应用中,我有一个Vue实例,该实例用作事件总线以在组件之间发送数据.

In my VueJS app I have a Vue instance which I'm using as an event bus for sending data between components.

就是这样:

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

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

Then in my components I import EventBus and use EventBus.$emit() and EventBus.$on().

此处介绍了此方法: https://alligator.io/vuejs/global-事件总线/

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

What I'd like to be able to do is listen to any event that is sent through EventBus. If I could bind one listener to all events I could use this for logging or to feed data into some system for my development environment that would show me all data as it went into eventBus, which would be super useful.

我是否缺少任何类型的 vm.$ listenToEverything()或通过某种方式可以实现此目的?

Is there any type of vm.$listenToEverything() that I'm missing or some way to make this work?

推荐答案

如果您使用的是ES6上下文,则可以采用以下两种方法之一.我通过评论来解释.

If you're in an ES6 context, you could take either of below approaches. I explain through comments.

'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 ,换句话说,猴子补丁方法,而不是直接覆盖它们.

Override through hijacking

Or using a "hijacking" factory class in case you don't want your Vue event bus to be wrapped. The logic is basically the same, however, in this approach we hijack, or in other words, monkey patch the methods instead of overriding them directly.

'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()

这篇关于如何在VueJS中监听所有自定义事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆