import mitt from 'mitt'
import { onBeforeUnmount } from 'vue'
interface Option {
name: string // 事件名称
callback: Fn // 回调
}
const emitter = mitt()
export const useEventBus = (option?: Option) => {
if (option) {
emitter.on(option.name, option.callback)
onBeforeUnmount(() => {
emitter.off(option.name)
})
}
return {
on: emitter.on,
off: emitter.off,
emit: emitter.emit,
all: emitter.all
}
}
使用安装mitt
npm install mitt
组件 A(触发事件):
<script setup>
import { useEventBus } from './path-to-useEventBus'; // 引入 useEventBus 函数
const { emit } = useEventBus();
const triggerEvent = () => {
emit('my-event', 'Hello from Component A!');
};
</script>
<template>
<button @click="triggerEvent">Send Event to Component B</button>
</template>
组件 B(监听事件):
<script setup>
import { useEventBus } from './path-to-useEventBus'; // 引入 useEventBus 函数
const { on, off } = useEventBus();
const handleEvent = (data) => {
console.log('Event received in Component B:', data);
};
on('my-event', handleEvent);
// 组件卸载时取消监听
onBeforeUnmount(() => {
off('my-event', handleEvent);
});
</script>
<template>
<!-- Component B's template content -->
</template>