pnpm add mitt
main.ts
中挂载全局属性import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
// 导入 mitt
import mitt from "mitt"
const app = createApp(App);
// 将 mitt 挂载到 Vue 实例上
app.config.globalProperties.$bus = mitt();
app.mount('#app')
<template>
<Hello1 />
<Hello2 />
<Hello3 />
<button @click="sendMsg">发消息</button>
</template>
<script setup lang="ts">
import Hello1 from "./components/Hello1.vue";
import Hello2 from "./components/Hello2.vue";
import Hello3 from "./components/Hello3.vue";
import {getCurrentInstance} from 'vue'
const bus = getCurrentInstance()?.appContext.config.globalProperties.$bus;
const sendMsg = () => {
bus.emit('hello1', 'hello1')
bus.emit('hello2', 'hello2')
bus.emit('hello3', 'hello3')
}
</script>
其他类似
<script setup lang="ts">
import {onBeforeUnmount, onMounted} from "vue";
import {getCurrentInstance} from 'vue'
const bus = getCurrentInstance()?.appContext.config.globalProperties.$bus;
// 组件挂载后监听事件
onMounted(() => {
// 监听事件
bus.on('hello1', (msg: any) => {
console.log(msg)
})
});
// 组件销毁前移除事件
onBeforeUnmount(() => {
bus.off('hello1')
})
</script>
<template>
<h1>hello1</h1>
</template>
<style scoped>
</style>
import mitt from 'mitt'
const emitter = mitt()
// listen to an event
emitter.on('foo', e => console.log('foo', e) )
// listen to all events
emitter.on('*', (type, e) => console.log(type, e) )
// fire an event
emitter.emit('foo', { a: 'b' })
// clearing all events
emitter.all.clear()
// working with handler references:
function onFoo() {}
emitter.on('foo', onFoo) // listen
emitter.off('foo', onFoo) // unlisten
import {onUnmounted} from 'vue'
import mitt from 'mitt'
type IUseEventbus = {
customEmit: (eventName: string) => void
customOn: (eventName: string, callback: () => void) => void
toRefreshTable: () => void
refreshTable: (callback: () => void) => void
}
const emitter = mitt();
/**
* @description: 自定义触发器
* @param {*} eventName 名称
*/
const customEmit = (eventName: string) => {
emitter.emit(eventName)
}
/**
* @description: 自定义接收器
* @param {*} name 名称
* @param {*} callback 回调的函数
*/
const customOn = (eventName: string, callback: () => void) => {
emitter.on(eventName, () => callback())
}
/**
* @description: 通知刷新表格数据
*/
const toRefreshTable = () => {
emitter.emit('refreshTable')
}
/**
* @description: 刷新表格数据
* @param {*} callback 回调的函数
*/
const refreshTable = (callback: () => void) => {
emitter.on('refreshTable', () => callback())
}
/**
* @description: 导出useEventbus
*/
export const useEventbus = (): IUseEventbus => {
// 销毁的事件
onUnmounted(() => {
// 清空所有的事件,避免多组件互相清理
emitter.all.clear()
})
return {
customEmit,
customOn,
toRefreshTable,
refreshTable
}
}
emitter.on
第一个参数是消息 key ,第二个参数可以是基本数据、对象、函数!