pnpm install mitt
mitt 主要有4个API:
emit
(触发某个事件)、on
(绑定事件)、off
(解绑某个事件)、all
(获取所有绑定的事件)
使用步骤:
(1)main.js中将mitt全局注册
(2)在A组件中emit 发射事件(发射信号)
(3)在B组件中监听事件
(4)移除监听
main.js 中通过 app.config.globalProperties
将 mitt 实例注册为全局属性。整个应用中的任何组件都可以方便地访问和使用事件总线,无需单独引入。
//main.js
import { createApp } from 'vue';
import App from './App.vue';
import mitt from 'mitt';
const app = createApp(App);
// 将 mitt 实例挂载到全局属性
app.config.globalProperties.$bus = mitt();
app.mount('#app');
App.vue 简版写法
<template>
<div>
<div v-if="showTaskLog">Task Log is shown</div>
<ChildComponent />
</div>
</template>
<script setup>
import { ref, getCurrentInstance } from 'vue';
const showTaskLog = ref(false); //显示/隐藏日志
const { proxy } = getCurrentInstance(); //setup 中可以通过 proxy 获取全局属性
proxy.$bus.on('show-task-log', data => { showTaskLog.value = true;}); //监听'show-task-log' 事件, 发生show-task-log事件就执行()=>{ showTaskLog.value = true;}
</script>
<!--
此方案没有使用 onUnmounted 来管理事件监听器的生命周期,潜在的内存泄漏问题。注册到全局变量,不会因为组件销毁而销毁,内存没有得到释放。
如果在组件卸载时你不需要移除事件监听器,或者你确定事件监听器的生命周期与组件的生命周期一致,这种简化方式是可以的。
-->
推荐使用 onMounted
和 onUnmounted
,这样可以确保组件卸载时不会出现内存泄漏。
App.vue 推荐写法
<!--App.vue-->
<template>
<div>
<div v-if="showTaskLog">Task Log is shown</div>
<ChildComponent />
</div>
</template>
<script setup>
import { ref, onMounted, onUnmounted, getCurrentInstance } from 'vue';
const showTaskLog = ref(false);
const { proxy } = getCurrentInstance();
onMounted(() => { proxy.$bus.on('show-task-log', ()=> {showTaskLog.value = true;});});
onUnmounted(() => { proxy.$bus.off('show-task-log');}); // 不指定移除哪个回调函数,就移除监听show-task-log的绑定的所有回调函数。
</script>
如果多个回调函数监听同一个事件,而onUmounted时只想移除特定的回调函数则需要这样写:
const handleShowTaskLog = () => {
console.log('handleShowTaskLog called');
};
const anotherHandler = () => {
console.log('anotherHandler called');
};
onMounted(() => {
proxy.$bus.on('show-task-log', handleShowTaskLog);
proxy.$bus.on('show-task-log', anotherHandler);
});
onUnmounted(() => {
proxy.$bus.off('show-task-log', handleShowTaskLog);
// 这样可以确保 only handleShowTaskLog 被移除,而 anotherHandler 仍然会被触发
});
发射
<template>
<button @click="triggerAsyncFunction">Show Task Log</button>
</template>
<script setup>
import { getCurrentInstance } from 'vue';
const { proxy } = getCurrentInstance();
const triggerAsyncFunction = async () => {
// 发射事件通知其他组件
proxy.$bus.emit('show-task-log');
// 模拟一个异步函数
await new Promise(resolve => setTimeout(resolve, 1000));
};
</script>