vue3全局组件通信 mitt的使用

74 阅读1分钟

首先需要引入实例

import {reactive, ref, onMounted, getCurrentInstance } from "vue"

使用时,在消息发送组件中注册并在触发动作那里发送消息

  • 在组件内注册: const bus=getCurrentInstance()?.appContext.config.globalProperties.bus = getCurrentInstance()?.appContext.config.globalProperties.mittBus

  • 发送消息: $bus.emit('eventName', event)

    同样的,在接收消息处的组件接受并触发内容,参数可以在event中通过arguments传入。

  • 在组件内注册: const bus=getCurrentInstance()?.appContext.config.globalProperties.bus = getCurrentInstance()?.appContext.config.globalProperties.mittBus

  • 接收消息: $bus.on('eventName', event => { console.log(event) })

  • event定义: {type: '事件类型',data: '事件内容'}

在组件关闭后,需要将消息取消。

  • 组件销毁时取消事件: onBeforeUnmount(() => { // 移除指定事件 bus.off(newTask)//移除所有事件bus.off('newTask') // 移除所有事件 bus.all.clear() })