【Vue3】vue3 事件总线mitt使用

一、前言

Vue2.x 使用 EventBus 事件总线进行兄弟组件通信,而在Vue3中事件总线模式已经被移除,官方建议使用外部的、实现了事件触发器接口的库,例如 mitt 或 tiny-emitter。

二、优势

  • 首先它足够小,仅有200bytes。
  • 其次支持全部事件的监听和批量移除。
  • 它还不依赖 Vue 实例,可以跨框架使用,React 或者 Vue,甚至 jQuery 项目都能使用同一套库。

三、使用

1.API
// 创建mitt实例
mitt()
// 事件名称到注册处理程序函数的映射。
all
//触发事件,两个参数:name:触发的方法名,data:需要传递的参数
emit(name,data) 
// 绑定事件,两个参数:name:绑定的方法名,callback:触发后执行的回调函数
on(name,callback) 
// 解绑事件,一个参数:name:需要解绑的方法名
off(name) 
2. 安装
npm i mitt -s
3.声明

main.js

import {
    
     createApp } from 'vue'
import mitt from 'mitt'
import App from './App.vue'

const app = createApp(App)
app.config.globalProperties.Bus = mitt()
app.mount('#app')
4. 传递信息
<template>
  <button @click="onclick">按钮</button>
</template>

<script setup>
import {
    
     getCurrentInstance, onBeforeMount } from 'vue'
// 获取到 全局事件总线
const {
    
     Bus }  = getCurrentInstance().appContext.config.globalProperties

const onclick = () => {
    
    
  Bus.emit('Event', {
    
     a: 'b' })
}
</script>
5. 接受信息
Bus.on('Event', (res)=>{
    
    
  // res 就是emit传过来的数据
  console.log(res)
})
6. 监听所有事件
Bus.on('*', (type, res)=>{
    
    
  // res 就是emit传过来的数据
  console.log(type, res)
})
7. 移除监听事件
Bus.off('Event');
8. 清空所有事件
Bus.all.clear();

四、Typescript使用

import mitt from 'mitt';

type Events = {
    
    
  foo: string;
  bar?: number;
};

const emitter = mitt<Events>(); // inferred as Emitter<Events>

emitter.on('foo', (e) => {
    
    }); // 'e' has inferred type 'string'

emitter.emit('foo', 42); // Error: Argument of type 'number' is not assignable to parameter of type 'string'. (2345)

或者

import mitt, {
    
     Emitter } from 'mitt';

type Events = {
    
    
  foo: string;
  bar?: number;
};

const emitter: Emitter<Events> = mitt<Events>();

猜你喜欢

转载自blog.csdn.net/qq_36012563/article/details/127449802