35 lines
791 B
TypeScript
35 lines
791 B
TypeScript
import type { EventBusHandler } from '~/extends/EventBusExtend'
|
|
|
|
/**
|
|
* 事件总线组合式封装
|
|
* 在组件作用域内订阅时会自动解绑
|
|
*/
|
|
export const useEventBus = () => {
|
|
const registerDispose = (unsubscribe: () => void) => {
|
|
if (getCurrentScope()) {
|
|
onScopeDispose(unsubscribe)
|
|
}
|
|
|
|
return unsubscribe
|
|
}
|
|
|
|
const on = <T = unknown>(event: string, handler: EventBusHandler<T>) => {
|
|
return registerDispose(EventBusExtend.on(event, handler))
|
|
}
|
|
|
|
const off = <T = unknown>(event: string, handler?: EventBusHandler<T>) => {
|
|
EventBusExtend.off(event, handler)
|
|
}
|
|
|
|
const emit = <T = unknown>(event: string, payload?: T) => {
|
|
EventBusExtend.emit(event, payload)
|
|
}
|
|
|
|
return {
|
|
on,
|
|
off,
|
|
emit,
|
|
clear: EventBusExtend.clear
|
|
}
|
|
}
|