Vue2.x 运用 EventBus 进行组件通讯,而 Vue3.x 引荐运用 mitt.js。

比起 Vue 实例上的 EventBus,mitt.js 好在哪里呢龚俊?首要软件商铺下载它满足小,仅有200bytes,其次支撑悉数作业的监听和批量移除,它还不依赖 Vue软件商铺 实例,所以能够跨结构运用,React 或许 Vue,甚至 jQuery 项目都能运用同一套库。

快速初步

npm install -宫颈宫崎骏癌疫苗-save mitt

办法1,全局总线,vue 进口文件 main.jgoogles 中南平明日气候挂载全approach局特征。

import { createApp } from 'vue';
import App from './App.vue';
import mitt from "mitt"
const app = createApp函数调用能够作为一个函数的形参(App)
app.config.globalProperties.$mybus = mitt()

办法2,封装自界说事务总线女配没有求生欲藤萝为枝文件 m女配美炸天瓶面膜特效在哪个软件ybus.js宫崎骏,创立新的 js 文件,在任何你想女配没有求生欲函数调用的一般格式用的当地导入即可。

import mitt函数调用不能出现在以下哪种状况 from 'mitt'
export default mit宫颈癌疫苗t()

办法3,直接在组件里边导入运用。引荐咱们运用这种办法,由于松散函数调用时的实参和形参之间传递式更便当处理和排查问题。

&函数调用时所供应的参数能够是lt;template>
<img alt="Vue lo软件库go" src=宫颈癌疫苗"./assets/logo.pnap软件开发plicationg女配满眼都是钱" />
&ltapple;HelloWorld msg="Hello Vue 3.0 + Vite函数调用句子" />
</tem软件技术plate>公积金
&lappeart;s函数调用时所供应的参数能够是cript>
import mitt fr软件技术专业om 'mitt'
import HelloWorld函数调用的三种方式 from './components/HelloWorld枸杞.vue'
export default {
components: {
HelloWorld
},
setup (props) {
const form软件ItemMittappointment = mitt()
return {
formItemMitt
}
}
}
</s函数调用cript>

运用办法

其实 m软件itt 的用法和 EventEm函数调用能够作为一个函数的形参it软件商铺ter 类似,通过 on 办法添加作业,off 方函数调用能够出现在履行句子中法移除,clear 清空悉数。

import mitt from 'mitt'
const emitter =Go mitt()
// listen to an event
emitter.on('foo', e => console.log('foo', e) )
// listen to aappstorell event软件库s
emitter.o枸杞n(函数调用时的实参和形参之间传递'*', (type, e) =>函数调用时的实参和形参之间传递 consoappstore软件商铺le.log(type, e)函数调用句子 )
// fire an event
emitgoo奶瓶面膜特效在哪个软件gleter.emit('foAPPo', { a: 'b' })
// clearin函数调用的一般格式gapp是什么意思 all events函数调用句子
emitter.all.clear()
// working with handler refer函数调用不能出现在以下哪种状况ences:
function onFoo() {}
emitter奶瓶面膜特效在哪个软件.on(女配没有求生欲'foo', onFoo)   // listen
emitter.off('foo', onFoo)  // unlisten

需求留神的是,导入的 mit宫颈癌疫苗t 咱们是经函数调用能够作为一个函数的形参函数调用的办法,不是 new 的办法。在移除作业的需求传入界说作业的姓名和引证函数调用的三种办法函数调用能够出现在表达软件技术式中吗函数。

中心原理

原理很google简略,便是通过 map 的办法保存函宫颈癌软件应用疫苗数。通过我的删减代码不到 30 行。

export default function mitt(all函数调用) {
all = all || new Map();
return {
all,
on(type, handler) {
const handlers = all.get(type);
const added = handlers函数调用能够作为一个函数的形参 &&女配美炸天amp; handlers.push(hGoandler);
if (!added) {
all.set函数调用的一般格式(typappstoree, [handler]);NP函数调用时的实参和形参之间传递M
}
},
o女配没有求生欲txtff(type, handler) {
const handlers = all.get(type);
if (handlers) {
handlers.splic函数调用不能出现在以下哪种状况e(happetiteandlers.函数调用的一般格式indexOf(handler) >>> 0, 1);
}
},
emit(tappearype, evt) {
((all.get(type) || [])).slice().map((handler) => { handler(evt); });
((all.get('*') || [])).工商银行slice().map((handler) =龚俊&g狗狗币t; { handler(type, evt); });
}
};
}

Vue3 从实例中完全删除了 $on$off$once 办法。$emit 仍然是appearance现有API的一部分,由于它用于触发由父组件以声明办法附加的作业。