Using EventBus (event bus) in vue

Requirements: The most common data transfer in Vue components is the transfer between parent and child components. The parent component can pass data down to the child component through props, and the child component can carry data to the parent component through the $emit event. However, how should two pages communicate when they have no relationship ? This leads to the concept of EventBus (event bus)

Here we introduce the usage of event bus in Vue2 and Vue3 respectively.

Use in Vue2

Introduction to EventBus
EventBus, also known as event bus, is equivalent to a global warehouse. Any component can go to this warehouse to obtain event
initialization .

Method 1: Create a new file.
First, you need to initialize an EventBus and share a Vue instance object.
Create a new js file, such as: EventBus.js

// src/utils/EventBus.js 文件
import Vue from 'vue'
 
// 向外共享 Vue 的实例对象
export default new Vue()

Method 2: Mount on the prototype of Vue

Initialize EventBus in main.js

// src/main.js
 
Vue.prototype.$EventBus = new Vue()
 

The code to pass the data
A component is as follows:

<template>
  <div>
    <button @click="send">点我发送消息</button>
  </div>
</template>
 
<script>
import EventBus from '@/utils/EventBus'
 
export default {
    
    
  data:()=>({
    
    
    a_data: 'message'
  }),
  methods: {
    
    
    send () {
    
    
      EventBus.$emit('share', this.a_data);
    }
  }
}
</script>

The code of component B is as follows:

<template>
  <div>
  <h1>{
    
    {
    
     b_data }}</h1>
  </div>
</template>
 
<script>
import EventBus from '@/utils/EventBus'
 
export default {
    
    
  data: () => ({
    
    
    b_data: null
  }),
  created () {
    
    
    EventBus.$on('share', value => {
    
    
      // 将 A 组件传递过来的数据保存到 B 组件
      this.b_data = value;
    })
  },
  beforeDestroy() {
    
    
    // 移除监听事件 "share"
    EventBus.$off('share')
  }
}
</script>

Note:
In short, component A only sent an event to EventBus once, but component B listened multiple times. There are many identical event listeners in the EventBus container. At this time, the event is only triggered once, but the listening event The callback function in has been executed many times
1. Solution: Remove the listening event before the component leaves, that is, before it is destroyed, so as not to create the listening event again next time.
2. Syntax: EventBus.$off(to be removed The event name to be monitored)

Use in Vue3

The EventBus we just mentioned cannot be used to create a bus in vue3. We use the third-party plug-in Mitt here. Mitt
is a small event bus library used in Vue.js applications. This library allows components to communicate without having to rely heavily on props between parent or child components.

Introduction to the features and functions of Mitt
Lightweight: Mitt is only 200 bytes in size, which will not increase the burden on your application.
Easy to use: you only need to introduce mitt and configure it to use.
Support any Javascript environment: Mitt supports any Javascript environment. Used below, not limited to Vue
application scenarios: component communication

Introducing Mitt

Install dependencies

Execute installation command

npm install --save mitt

Under the src directory, create a new /utils/bus.js with the following content:

// 事件总线第三方库:
import mitt from 'mitt'

const bus = mitt()
export default bus

use:

import bus from '@/utils/bus.js'

//in component A 触发
bus.emit('event-name', eventData)

//in component B 监听
bus.on('event-name', eventData => {
    
     /* do something with eventData */ })

// 页面卸载的时候取消本次监听
bus.off('event-name'eventData => {
    
     /* do something with eventData */ })

If we use TS syntax, mitt here is used as follows
. Under the src directory, create a new /utils/bus.ts with the following content:

// https://www.npmjs.com/package/mitt
import mitt, {
    
     Emitter } from 'mitt';

// 类型
const emitter: Emitter<MittType> = mitt<MittType>();

// 导出
export default emitter;

Use as follows:

<script setup lang="ts" name="layoutBreadcrumbUser">
import mittBus from '/@/utils/mitt';

//in component A 触发
mittBus.emit('closeAllTagsView')

//in component B 监听
mittBus.on('closeAllTagsView', eventData => {
    
     /* do something with eventData */ })

页面卸载的时候取消本次监听
mittBus.off('closeAllTagsView', eventData => {
    
     /* do something with eventData */ })
</script >

Guess you like

Origin blog.csdn.net/qq_44552416/article/details/133274314