A lightweight EventBus with auto-unsubscribe and Vue lifecycle integration.
npm install smart-event-busbash
pnpm install smart-event-bus
`
---
使用示例
$3
`ts
import { useEventBus, emitEvent } from 'smart-event-bus'
useEventBus('hello', (msg) => {
console.log('收到消息:', msg)
})
emitEvent('hello', '你好,Vue3')
`
$3
`ts
`
$3
`ts
// 防抖 500ms
useEventBus('input', (val) => {
console.log('防抖输入:', val)
}, { debounce: 500 })
// 节流 1s
useEventBus('scroll', () => {
console.log('节流触发滚动')
}, { throttle: 1000 })
`
$3
`ts
useEventBus('click', () => {
console.log('只触发 3 次')
}, { maxCalls: 3, debug: true })
`
$3
`ts
onceEvent('init', () => {
console.log('仅第一次触发')
})
`
$3
`ts
import { createNamespacedBus } from 'smart-event-bus'
const authBus = createNamespacedBus('auth')
authBus.on('login', (user) => console.log(user))
authBus.emit('login', { id: 1, name: 'Jack' })
`
$3
`ts
emitEvent('ready', '数据准备好了') // 监听器未挂载
useEventBus('ready', (msg) => console.log(msg), { buffer: true })
// 控制台立即打印:数据准备好了
`
$3
`ts
useEventBus('save', (data) => console.log('已保存:', data), {
middleware: (payload) => {
if (!payload.valid) return false // 阻止事件
payload.savedAt = Date.now()
return payload
}
})
emitEvent('save', { valid: true })
`
---
API 文档
$3
在组件中注册监听函数,并在组件卸载时自动取消订阅。
| 参数 | 类型 | 说明 |
| --------- | ------------------------ | --------------- |
| event | string | 事件名称 |
| handler | (payload: any) => void | 事件处理函数 |
| options | EventBusOptions(可选) | 控制节流、防抖、限制次数等配置 |
$3
触发指定事件,传递参数。
$3
只执行一次的事件订阅。
$3
移除指定事件的所有监听器,或全部清空。
$3
创建带命名空间的事件总线实例,防止事件冲突。
---
EventBusOptions 配置项
`ts
interface EventBusOptions {
debounce?: number // 防抖间隔时间(ms)
throttle?: number // 节流间隔时间(ms)
maxCalls?: number // 最多触发次数
debug?: boolean // 控制台调试信息输出
buffer?: boolean // 是否接收事件缓冲(先触发后监听)
middleware?: (payload: any) => any | false // 中间件拦截器,返回 false 阻止事件
}
``