Skip to content

useEventBus

类别
导出大小
289 B
最近修改
2 days ago

基本的事件总线。

🌐 A basic event bus.

示例

News channel:
Television:
--- no signal ---

用法

🌐 Usage

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 内注册的监听器将在组件卸载时自动注销。

🌐 Listeners registered inside of components setup will be unregistered automatically when the component gets unmounted.

TypeScript

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

🌐 Using EventBusKey is the key to bind the event type to the key, similar to Vue's InjectionKey util.

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 }` })