多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
>[success] # 全局事件总线mitt库 1. Vue3从实例中移除了 `$on`、`$off `和` $once` 方法,Vue3官方有推荐一些库,例如[mitt](https://github.com/developit/mitt)或[tiny-emitter](https://github.com/scottcorgan/tiny-emitter)。 2. 之前使用 [Bus](https://www.kancloud.cn/cyyspring/vuejs/943729),实现方法也已经失效,因为之前bus 使用的是vue 实例上的 `$on` 方法进行分发 3. [mitt](https://github.com/developit/mitt)或[tiny-emitter](https://github.com/scottcorgan/tiny-emitter)。主要作用是**可以跨组件层级传值,或者跨越兄弟组件传值** [参考vue 使用`$on`](https://www.kancloud.cn/cyyspring/vuejs/1009440) >[danger] ##### 使用案例 安装`npm install tiny-emitter` * 在 src/utils 文件目录创建了`event-bus.js` ~~~ import emitter from 'tiny-emitter/instance' // 封装一层 名字更像以前的 bus export default { $on: (...args) => emitter.on(...args), $once: (...args) => emitter.once(...args), $off: (...args) => emitter.off(...args), $emit: (...args) => emitter.emit(...args), } ~~~ * 在子组件(兄弟组件/孙子组件) ~~~ <template> <div> {{ msg }} </div> </template> <script> import bus from '@/utils/event-bus' export default { name: 'HelloWorld', data() { return { msg: '123', } }, methods: { changeMsg(msg) { this.msg = msg }, }, mounted() { // 注册触发事件 bus.$on('changeMsg', this.changeMsg) }, unmounted() { // 销毁触发事件 bus.$off('changeMsg', this.changeMsg) }, } </script> ~~~ * 父组件调用 ~~~ <template> <HelloWorld /> <button @click="parentChange">改变</button> </template> <script> import HelloWorld from './components/HelloWorld.vue' import bus from '@/utils/event-bus' export default { name: 'App', components: { HelloWorld, }, methods: { parentChange() { bus.$emit('changeMsg', '789') }, }, } </script> <style></style> ~~~ >[info] ## 官网对应 [参考](https://v3-migration.vuejs.org/zh/breaking-changes/events-api.html)