Vue3使用事件总线
写在前面
vue3 不再默认支持事件总线
在 vue3 使用事件总线的步骤
- 引入/编写事件库
- 在入口文件中挂载
- 在组件中引入并使用
具体实现
- 引入 mitt 插件
shell
pnpm add mitt
- 编写
emitter.ts
ts
// emitter.ts
import mitt from 'mitt'
const emitter = mitt()
export default emitter
然后就可以定义发起和接收的相关事件了,常用的 API 和参数如下:
| 方法名 | 说明 |
|---|---|
| on | 注册一个监听事件,用于接收数据 |
| emit | 调用方法发起数据传递 |
| off | 用来移除监听事件 |
on 方法参数
| 参数名 | 类型 | 说明 |
|---|---|---|
| type | string 或 symbol | 自定义事件名 |
| handler | function | 自定义事件处理函数 |
handler 建议使用具名函数,因为匿名函数无法销毁。
emit 方法参数
| 参数名 | 类型 | 说明 |
|---|---|---|
| type | string 或 symbol | 自定义事件名 |
| data | any | 与 on 对应的,允许接收的数据 |
off 方法参数
| 参数名 | 类型 | 说明 |
|---|---|---|
| type | string 或 symbol | 自定义事件名 |
| handler | function | 要删除的事件函数,与 on 对应的 handler 函数名 |
- 基本使用
ts
import { defineComponent, onBeforeUnmount } from 'vue'
import emitter from './emitter.ts'
export default defineComponent({
setup() {
// 定义一个打招呼的方法
const sayHi = (msg: string = 'Hello World!'): void => {
console.log(msg)
}
// 启用监听
emitter.on('sayHi', sayHi)
// 在组件卸载之前移除监听
onBeforeUnmount(() => {
emitter.off('sayHi', sayHi)
})
},
})
ts
import { defineComponent } from 'vue'
import emitter from './emitter.ts'
export default defineComponent({
setup() {
// 调用打招呼事件,传入消息内容
emitter.emit('sayHi', '哈哈哈哈哈哈哈哈哈哈哈哈哈哈')
},
})