在vue3中$on,$off 和 $once 实例方法已被移除,组件实例不再实现事件触发接口,因此大家熟悉的EventBus便无法使用了。然而我们习惯了使用EventBus,对于这种情况我们可以使用Mitt库(其实就是我们视频中讲的发布订阅模式的设计)
1.安装
2.main.ts 初始化
全局总线,vue 入口文件 main.js 中挂载全局属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| import { createApp } from 'vue' import App from './App.vue' import mitt from 'mitt'
const Mit = mitt()
declare module "vue" { export interface ComponentCustomProperties { $Bus: typeof Mit } }
const app = createApp(App)
app.config.globalProperties.$Bus = Mit
app.mount('#app')
|
3使用方法通过emit派发, on 方法添加事件,off 方法移除,clear 清空所有
A组件派发(emit)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| <template> <div> <h1>我是A</h1> <button @click="emit1">emit1</button> <button @click="emit2">emit2</button> </div> </template>
<script setup lang='ts'> import { getCurrentInstance } from 'vue' const instance = getCurrentInstance(); const emit1 = () => { instance?.proxy?.$Bus.emit('on-num', 100) } const emit2 = () => { instance?.proxy?.$Bus.emit('*****', 500) } </script>
<style> </style>
|
B组件监听(on)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <template> <div> <h1>我是B</h1> </div> </template>
<script setup lang='ts'> import { getCurrentInstance } from 'vue' const instance = getCurrentInstance() instance?.proxy?.$Bus.on('on-num', (num) => { console.log(num,'===========>B') }) </script>
<style> </style>
|
监听所有事件( on(“*“) )
1 2 3
| instance?.proxy?.$Bus.on('*',(type,num)=>{ console.log(type,num,'===========>B') })
|
移除监听事件(off)
1 2 3 4 5
| const Fn = (num: any) => { console.log(num, '===========>B') } instance?.proxy?.$Bus.on('on-num',Fn)//listen instance?.proxy?.$Bus.off('on-num',Fn)//unListen
|
清空所有监听(clear)
1
| instance?.proxy?.$Bus.all.clear()
|
本文转自 https://xiaoman.blog.csdn.net/article/details/125453908?spm=1001.2014.3001.5502,如有侵权,请联系删除。