前提:在vue2中使用EventBus,而在Vue3中事件总线模式已经被移除,在vue3我们可以使用mitt库来替代。
一、安装
npm install mitt -S
二、引入
// main.js
import mitt from 'mitt'
const mitt = mitt()
app.config.globalProperties.$mitt = mitt
三、使用
// A组件
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance()
const mitt = proxy.$mitt
const fn = (val) => {
console.log(val) // true
}
mitt.on('changeBool',fn) // 监听事件
Bus.on('*', (type, res)=>{ // 监听所有事件
// res 就是emit传过来的数据
console.log(type, res)
})
mitt.off('changeBool') // 移除此项监听事件
mitt.all.clear() // 清空所有事件
// B组件
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance()
const mitt = proxy.$mitt
mitt.emit('changeBool',true)