# 事件总线
轻量级的 Event Bus。
# 如何使用
安装:
pnpm add ebus-light
使用方式有以下几种。
- 直接引入
bus
是全局唯一的实例。
import { bus } from 'ebus-light';
bus.emit('foo', { name: 'yang' });
function onFoo(e) {
console.log(e.name);
}
bus.on('foo', onFoo)
bus.off('foo', onFoo)
- Vue 插件
也可当作 Vue
插件,先在 main.ts
中注册:
import { eventBus } from 'ebus-light';
app.use(eventBus);
在页面中使用:
// options API
export default {
mounted() {
this.$eventBus.emit('foo')
}
}
通过 inject
访问:
import `inject` from 'vue';
export default {
setup() {
const bus = inject('$eventBus');
bus.emit('foo');
}
}
# 类型
通过插件方式使用时传递的参数:
export interface Options {
// 是否挂载在全局
global?: boolean;
// 是否 provide
inject?: boolean;
// 实例上挂载的名称
globalPropertyName?: string;
// 通过 inject 引入的名称
injectName?: string;
}
参数默认值:
const DEFAULT_OPTIONS = {
global: false,
inject: false,
globalPropertyName: '$eventBus',
injectName: '$eventBus',
};