vue3 使用mitt事件总线,传递不同组件数据
Mitt 是一个在 Vue.js 应用程序中使用的小型事件总线库。该库允许组件进行通信,而不必过度依赖父级或子级组件之间的 props。中,事件总线(Event Bus)不再像 Vue 2 那样直接依赖。,因为 Vue 3 移除了。
·
在 Vue 3 中,事件总线(Event Bus)不再像 Vue 2 那样直接依赖 $emit
和 $on
,因为 Vue 3 移除了 $on
和 $off
方法。但你仍然可以使用 mitt 或者 EventTarget
来实现事件总线。
Mitt 是一个在 Vue.js 应用程序中使用的小型事件总线库。该库允许组件进行通信,而不必过度依赖父级或子级组件之间的 props。
安装插件
npm install mitt
使用
main.js
const app = createApp(App)
app.config.globalProperties.$eventBus = new mitt() // 创建全局事件总线对象
触发:
<script setup>
import {getCurrentInstance} from "vue";
//js版本
const $eventBus = getCurrentInstance()?.appContext?.config?.globalProperties?.$eventBus;
//ts版本
const {$eventBus} = getCurrentInstance()!.appContext.config.globalProperties
function popUp(){
// 触发事件总线
$eventBus.emit('changeRobot', '1');
}
</script>
监听:
<script setup>
import {getCurrentInstance} from "vue";
const $eventBus = getCurrentInstance()?.appContext?.config?.globalProperties?.$eventBus;
// 事件总线监听
$eventBus.on('changeRobot',(data)=>{
console.log(data)
})
</script>
监听的页面需要卸载:
// 在组件销毁时注销事件总线消息
onBeforeUnmount(() => {
$eventBus.off('changeRobot')
});
或者
onUnmounted(() => {
eventBus.off('changeRobott', handleEvent);
});

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐
所有评论(0)