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>
到此这篇关于vue3 组件间通信之mitt实现任意组件间通信的文章就介绍到这了,更多相关vue3 mitt任意组件通信内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论