跳到主要内容

useEventBus

分类
导出大小
282 B
上次更改
3 个月前

一个基本的事件总线。

演示

新闻频道
电视
--- 无信号 ---

用法

ts
import { 
useEventBus
} from '@vueuse/core'
const
bus
=
useEventBus
<string>('news')
function
listener
(
event
: string) {
console
.
log
(`news: ${
event
}`)
} // listen to an event const
unsubscribe
=
bus
.
on
(
listener
)
// fire an event
bus
.
emit
('The Tokyo Olympics has begun')
// unregister the listener
unsubscribe
()
// or
bus
.
off
(
listener
)
// clearing all listeners
bus
.
reset
()
js
import { useEventBus } from '@vueuse/core'
const bus = useEventBus('news')
function listener(event) {
  console.log(`news: ${event}`)
}
// listen to an event
const unsubscribe = bus.on(listener)
// fire an event
bus.emit('The Tokyo Olympics has begun')
// unregister the listener
unsubscribe()
// or
bus.off(listener)
// clearing all listeners
bus.reset()

在组件 setup 中注册的监听器会在组件卸载时自动注销。

TypeScript

使用 EventBusKey 是将事件类型绑定到键的关键,类似于 Vue 的 InjectionKey 工具。

ts
// fooKey.ts
import type { 
EventBusKey
} from '@vueuse/core'
export const
fooKey
:
EventBusKey
<{
name
:
foo
}> =
Symbol
('symbol-key')
js
export const fooKey = Symbol('symbol-key')
ts
import { 
useEventBus
} from '@vueuse/core'
import {
fooKey
} from './fooKey'
const
bus
=
useEventBus
(
fooKey
)
bus
.
on
((
e
) => {
// `e` will be `{ name: foo }` })

类型声明

显示类型声明
ts
export type 
EventBusListener
<
T
= unknown,
P
= any> = (
event
:
T
,
payload
?:
P
,
) => void export type
EventBusEvents
<
T
,
P
= any> =
Set
<
EventBusListener
<
T
,
P
>>
export interface
EventBusKey
<
T
> extends Symbol {}
export type
EventBusIdentifier
<
T
= unknown> =
EventBusKey
<
T
> | string | number
export interface
UseEventBusReturn
<
T
,
P
> {
/** * Subscribe to an event. When calling emit, the listeners will execute. * @param listener watch listener. * @returns a stop function to remove the current callback. */
on
: (
listener
:
EventBusListener
<
T
,
P
>) =>
Fn
/** * Similar to `on`, but only fires once * @param listener watch listener. * @returns a stop function to remove the current callback. */
once
: (
listener
:
EventBusListener
<
T
,
P
>) =>
Fn
/** * Emit an event, the corresponding event listeners will execute. * @param event data sent. */
emit
: (
event
?:
T
,
payload
?:
P
) => void
/** * Remove the corresponding listener. * @param listener watch listener. */
off
: (
listener
:
EventBusListener
<
T
>) => void
/** * Clear all events */
reset
: () => void
} export declare function
useEventBus
<
T
= unknown,
P
= any>(
key
:
EventBusIdentifier
<
T
>,
):
UseEventBusReturn
<
T
,
P
>

来源

源码演示文档

贡献者

Anthony Fu
Anthony Fu
TuiMao233
NoiseFan
SerKo
jahnli
丶远方
Haoqun Jiang
sun0day
webfansplz
Jairo Blatt

更新日志

v13.6.0
d32f8 - refactor: 为所有纯函数添加 @__NO_SIDE_EFFECTS__ 注释 (#4907)
0a9ed - feat!: 放弃对 Vue 2 的支持,优化打包并清理 (#4349)

根据 MIT 许可证发布。