简体   繁体   English

Vue.js 3 事件总线

[英]Vue.js 3 Event Bus

How to create Event Bus in Vue 3?如何在 Vue 3 中创建事件总线?


In Vue 2, it was:在 Vue 2 中,它是:

export const bus = new Vue();
bus.$on(...)
bus.$emit(...)

In Vue 3, Vue is not a constructor anymore, and Vue.createApp({});在 Vue 3 中, Vue不再是构造函数,而Vue.createApp({}); returns an object that has no $on and $emit methods.返回一个没有$on$emit方法的 object。

As suggested in official docs you could use mitt library to dispatch events between components, let suppose that we have a sidebar and header which contains a button that close/open the sidebar and we need that button to toggle some property inside the sidebar component:正如官方文档中所建议的,您可以使用mitt库在组件之间调度事件,假设我们有一个侧边栏和header ,其中包含一个关闭/打开侧边栏的按钮,我们需要该按钮来切换侧边栏组件内的某些属性:

in main.js import that library and create an instance of that emitter and define as a global property :在 main.js 中导入该库并创建该发射器的实例并定义为全局属性

Installation:安装:

npm install --save mitt

Usage:用法:

import { createApp } from 'vue'
import App from './App.vue'
import mitt from 'mitt';
const emitter = mitt();
const app = createApp(App);
app.config.globalProperties.emitter = emitter;
app.mount('#app');

in header emit the toggle-sidebar event with some payload:在 header 中发出带有一些有效负载的toggle-sidebar事件:

<template>
  <header>
    <button @click="toggleSidebar"/>toggle</button>
  </header>
</template>
<script >
export default { 
  data() {
    return {
      sidebarOpen: true
    };
  },
  methods: {
    toggleSidebar() {
      this.sidebarOpen = !this.sidebarOpen;
      this.emitter.emit("toggle-sidebar", this.sidebarOpen);
    }
  }
};
</script>

In sidebar receive the event with the payload:在侧边栏中接收带有有效负载的事件:

<template>
  <aside class="sidebar" :class="{'sidebar--toggled': !isOpen}">
  ....
  </aside>
</template>
<script>
export default {
  name: "sidebar",
  data() {
    return {
      isOpen: true
    };
  },
  mounted() { 
    this.emitter.on("toggle-sidebar", isOpen => {
      this.isOpen = isOpen;
    });
  }
};
</script>

For those using composition api they could use emitter as follows:对于那些使用组合物 api 的人,他们可以使用emitter ,如下所示:

Create a file src/composables/useEmitter.js创建一个文件 src/composables/useEmitter.js

import { getCurrentInstance } from 'vue'

export default function useEmitter() {
    const internalInstance = getCurrentInstance(); 
    const emitter = internalInstance.appContext.config.globalProperties.emitter;

    return emitter;
}

And from there on you can use useEmitter just like you would with useRouter :从那里你可以像使用useEmitter一样使用useRouter

import useEmitter from '@/composables/useEmitter'

export default {
  setup() {
    const emitter = useEmitter()
    ...
  }
  ...
}

Using the composition API使用组合API

You could also take benefit from the new composition API and define a composable event bus:您还可以从新组合 API 中受益并定义一个可组合的事件总线:

eventBus.js事件总线.js

import { ref } from "vue";
const bus = ref(new Map());

export default function useEventsBus(){

    function emit(event, ...args) {
        bus.value.set(event, args);
    }

    return {
        emit,
        bus
    }
}

in component A do:在组件 A 中:

import useEventsBus from './eventBus';
...
//in script setup or inside the setup hook
const {emit}=useEventsBus()
...
 emit('sidebarCollapsed',val)

in component B:在组件 B 中:

const { bus } = useEventsBus()

watch(()=>bus.value.get('sidebarCollapsed'), (val) => {
  // destruct the parameters
    const [sidebarCollapsedBus] = val ?? []
    sidebarCollapsed.value = sidebarCollapsedBus
})

On version 3 of Vue.js, you can use either a third-party library, or use the functionality written in the publisher-subscriber(PubSub concept) programming pattern.在 Vue.js 的版本 3 上,您可以使用第三方库,或使用以发布者-订阅者(PubSub 概念)编程模式编写的功能。

event.js事件.js

//events - a super-basic Javascript (publish subscribe) pattern

class Event{
    constructor(){
        this.events = {};
    }

    on(eventName, fn) {
        this.events[eventName] = this.events[eventName] || [];
        this.events[eventName].push(fn);
    }

    off(eventName, fn) {
        if (this.events[eventName]) {
            for (var i = 0; i < this.events[eventName].length; i++) {
                if (this.events[eventName][i] === fn) {
                    this.events[eventName].splice(i, 1);
                    break;
                }
            };
        }
    }

    trigger(eventName, data) {
        if (this.events[eventName]) {
            this.events[eventName].forEach(function(fn) {
                fn(data);
            });
        }
    }
}

export default new Event();

index.js index.js

import Vue from 'vue';
import $bus from '.../event.js';

const app = Vue.createApp({})
app.config.globalProperties.$bus = $bus;

Content of EventBus class file: EventBus class 文件的内容:

class EventBusEvent extends Event {
  public data: any

  constructor({type, data} : {type: string, data: any}) {
    super(type)
    this.data = data
  }
}

class EventBus extends EventTarget {
  private static _instance: EventBus

  public static getInstance() : EventBus {
    if (!this._instance) this._instance = new EventBus()
    return this._instance
  }

  public emit(type : string, data?: any) : void {
    this.dispatchEvent(new EventBusEvent({type, data}))
  }
}

export default EventBus.getInstance()

usage in project, emit event:在项目中使用,发出事件:

import EventBus from '...path to eventbus file with class'
//...bla bla bla... code...
EventBus.emit('event type', {..some data..}')

listen event:监听事件:

import EventBus from '...path to eventbus file with class' 
//...bla bla bla... code...
EventBus.addEventListener('event type', (event) => { console.log(event.data) })

I've adapted another answer to have an equivalent interface to a Vue instance so that the utility works as a drop-in replacement that doesn't require changes in the consuming code.我已经调整了另一个答案,以具有与 Vue 实例等效的接口,以便该实用程序可以作为不需要更改使用代码的直接替代品。

This version also supports the $off method with the first argument being an array of event names.此版本还支持$off方法,第一个参数是事件名称数组 It also avoids an issue in the $off method were de-registering multiple event listeners would actually delete a wrong one due to iterating over the array in forwards direction while also deleting items from it.它还避免了$off方法中的一个问题,即取消注册多个事件侦听器实际上会删除错误的事件侦听器,因为在向前方向上迭代数组同时还会从中删除项目。

event-bus.js : event-bus.js

// @ts-check

/**
 * Replacement for the Vue 2-based EventBus.
 *
 * @template EventName
 */
class Bus {
  constructor() {
    /**
     * @type {Map<EventName, Array<{ callback: Function, once: boolean }>>}
     */
    this.eventListeners = new Map()
  }

  /**
   * @param {EventName} eventName
   * @param {Function} callback
   * @param {boolean} [once]
   * @private
   */
  registerEventListener(eventName, callback, once = false) {
    if (!this.eventListeners.has(eventName)) {
      this.eventListeners.set(eventName, [])
    }

    const eventListeners = this.eventListeners.get(eventName)
    eventListeners.push({ callback, once })
  }

  /**
   * See: https://v2.vuejs.org/v2/api/#vm-on
   *
   * @param {EventName} eventName
   * @param {Function} callback
   */
  $on(eventName, callback) {
    this.registerEventListener(eventName, callback)
  }

  /**
   * See: https://v2.vuejs.org/v2/api/#vm-once
   *
   * @param {EventName} eventName
   * @param {Function} callback
   */
  $once(eventName, callback) {
    const once = true
    this.registerEventListener(eventName, callback, once)
  }

  /**
   * Removes all event listeners for the given event name or names.
   *
   * When provided with a callback function, removes only event listeners matching the provided function.
   *
   * See: https://v2.vuejs.org/v2/api/#vm-off
   *
   * @param {EventName | EventName[]} eventNameOrNames
   * @param {Function} [callback]
   */
  $off(eventNameOrNames, callback = undefined) {
    const eventNames = Array.isArray(eventNameOrNames) ? eventNameOrNames : [eventNameOrNames]

    for (const eventName of eventNames) {
      const eventListeners = this.eventListeners.get(eventName)

      if (eventListeners === undefined) {
        continue
      }

      if (typeof callback === 'function') {
        for (let i = eventListeners.length - 1; i >= 0; i--) {
          if (eventListeners[i].callback === callback) {
            eventListeners.splice(i, 1)
          }
        }
      } else {
        this.eventListeners.delete(eventName)
      }
    }
  }

  /**
   * See: https://v2.vuejs.org/v2/api/#vm-emit
   *
   * @param {EventName} eventName
   * @param {any} args
   */
  $emit(eventName, ...args) {
    if (!this.eventListeners.has(eventName)) {
      return
    }

    const eventListeners = this.eventListeners.get(eventName)
    const eventListenerIndexesToDelete = []
    for (const [eventListenerIndex, eventListener] of eventListeners.entries()) {
      eventListener.callback(...args)

      if (eventListener.once) {
        eventListenerIndexesToDelete.push(eventListenerIndex)
      }
    }

    for (let i = eventListenerIndexesToDelete.length - 1; i >= 0; i--) {
      eventListeners.splice(eventListenerIndexesToDelete[i], 1)
    }
  }
}

const EventBus = new Bus()

export default EventBus

old-event-bus.js : old-event-bus.js

import Vue from 'vue'

const EventBus = new Vue()

export default EventBus

example.js : example.js

// import EventBus from './old-event-bus.js'
import EventBus from './event-bus.js'

I just want to mention here that you can also use useEventBus defined by VueUse .在这里我只想提一下,你也可以使用VueUse定义的useEventBus

Here is one example for TypeScript so using an injection key.这是 TypeScript 的一个示例,因此使用注入密钥。

//myInjectionKey.ts
import type { EventBusKey } from '@vueuse/core'
export const myInjectionKey: EventBusKey<string> = Symbol('my-injection-key')

//emmitter
import { useEventBus } from '@vueuse/core'
import { mapInjectionKey } from "src/config/mapInjectionKey";

const bus = useEventBus(mapInjectionKey)
bus.emit("Hello")

//receiver
import { useEventBus } from '@vueuse/core'
import { mapInjectionKey } from "src/config/mapInjectionKey";
const bus = useEventBus(mapInjectionKey)
bus.on((e) => {
    console.log(e) // "Hello"
})

With Vue composition and defineEmit you can even make it easier:使用 Vue 组合和defineEmit ,你甚至可以让它变得更简单:

<!-- Parent -->
<script setup>
  import { defineEmit } from 'vue'
  const emit = defineEmit(['selected'])
  const onEmit = (data) => console.log(data)
</script>

<template>
    <btnList
        v-for="x in y"
        :key="x"
        :emit="emit"
        @selected="onEmit"
    />
</template>
<!-- Children (BtnList.vue) -->
<script setup>
  import { defineProps } from 'vue'
  const props = defineProps({
      emit: Function
  })
</script>

<template>
    <button v-for="x in 10" :key="x" @click="props.emit('selected', x)">Click {{ x }}</button>
</template>

I just showed it with one children, but you could pass though the emit function down to other children.我只是和一个孩子一起展示了它,但你可以将发射function 传递给其他孩子。

Using https://www.npmjs.com/package/vue-eventer means minimal code changes when migrating from Vue 2.x to Vue 3.0 (just initialization)...使用https://www.npmjs.com/package/vue-eventer意味着从 Vue 2.x 迁移到 Vue 3.0 时代码更改最少(仅初始化)...

// Vue 2.x
Vue.prototype.$eventBus = new Vue();

-> ->

// Vue 3.x
import VueEventer from 'vue-eventer';
YourVueApp.config.globalProperties.$eventBus = new VueEventer();

In a Vuejs project you can create a new file on the same root as App.vue and instanciate the Vue constructor.在 Vuejs 项目中,您可以在与 App.vue 相同的根目录中创建一个新文件并实例化 Vue 构造函数。

eventBus.js file eventBus.js 文件

import Vue from 'vue';
export default new Vue();

Then, you only have to import the event on every vue file you want to emit or receiving the event, like this:然后,您只需在要发出或接收事件的每个 vue 文件上导入事件,如下所示:

import EventBus from "../eventBus.js";

To just emit and receive the event use the $emit/$on mark要发出和接收事件,请使用 $emit/$on 标记

EventBus.$emit("evMsg", someData);
EventBus.$on("evMsg", (someData) => {});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM