Vue3.x 推荐使用 mitt.js

https://www.toutiao.com/i6974284154196328968/?tt_from=mobile_qq&utm_campaign=client_share&timestamp=1631458881&app=news_article&utm_source=mobile_qq&utm_medium=toutiao_ios&use_new_style=1&req_id=202109122301210101351572281883FE8D&share_token=EA5C177C-3EFB-4D90-ABF1-1C3EEF1CB495&group_id=6974284154196328968

源码

https://github.com/developit/mitt/releases

安装

npm install mitt

js

import mitt from ‘mitt’
export default mitt()

引入:

import mybus from “../myplugins/mybus”;

发送

mybus.emit(‘自定义事件名称’,’数据’);

接收

mybus.on(‘自定义事件名称’,data=>{
console.log(data);//接收到的数据
})

移除

mybus.off(‘自定义事件名称’);

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
复制代码
文档更新时间: 2023-03-28 16:09   作者:admin