Vue2.x 使用 EventBus 进行组件通讯,而 Vue3.x 推荐使用 mitt.js。javascript
比起 Vue 实例上的 EventBus,mitt.js 好在哪里呢?首先它足够小,仅有200bytes,其次支持所有事件的监听和批量移除,它还不依赖 Vue 实例,因此能够跨框架使用,React 或者 Vue,甚至 jQuery 项目都能使用同一套库。html
npm install --save mitt
复制代码
方式1,全局总线,vue 入口文件 main.js 中挂载全局属性。vue
import { createApp } from 'vue';
import App from './App.vue';
import mitt from "mitt"
const app = createApp(App)
app.config.globalProperties.$mybus = mitt()
复制代码
方式2,封装自定义事务总线文件 mybus.js,建立新的 js 文件,在任何你想使用的地方导入便可。java
import mitt from 'mitt'
export default mitt()
复制代码
方式3,直接在组件里面导入使用。推荐你们使用这种方式,由于分散式更方便管理和排查问题。npm
<template>
<img alt="Vue logo" src="./assets/logo.png" />
<HelloWorld msg="Hello Vue 3.0 + Vite" />
</template>
<script> import mitt from 'mitt' import HelloWorld from './components/HelloWorld.vue' export default { components: { HelloWorld }, setup (props) { const formItemMitt = mitt() return { formItemMitt } } } </script>
复制代码
其实 mitt 的用法和 EventEmitter 相似,经过 on 方法添加事件,off 方法移除,clear 清空全部。markdown
import mitt from 'mitt'
const emitter = mitt()
// listen to an event
emitter.on('foo', e => console.log('foo', e) )
// listen to all events
emitter.on('*', (type, e) => console.log(type, e) )
// fire an event
emitter.emit('foo', { a: 'b' })
// clearing all events
emitter.all.clear()
// working with handler references:
function onFoo() {}
emitter.on('foo', onFoo) // listen
emitter.off('foo', onFoo) // unlisten
复制代码
须要注意的是,导入的 mitt 咱们是经过函数调用的形式,不是 new 的方式。在移除事件的须要传入定义事件的名字和引用的函数。app
原理很简单,就是经过 map 的方法保存函数。通过个人删减代码不到 30 行。框架
export default function mitt(all) {
all = all || new Map();
return {
all,
on(type, handler) {
const handlers = all.get(type);
const added = handlers && handlers.push(handler);
if (!added) {
all.set(type, [handler]);
}
},
off(type, handler) {
const handlers = all.get(type);
if (handlers) {
handlers.splice(handlers.indexOf(handler) >>> 0, 1);
}
},
emit(type, evt) {
((all.get(type) || [])).slice().map((handler) => { handler(evt); });
((all.get('*') || [])).slice().map((handler) => { handler(type, evt); });
}
};
}
复制代码
Vue3 从实例中彻底删除了 $on
、$off
和 $once
方法。$emit
仍然是现有API的一部分,由于它用于触发由父组件以声明方式附加的事件。函数