Skip to content

useBroadcastChannel

类别
导出体积
917 B
上次更改
7 months ago

响应式 BroadcastChannel API

在组件卸载时自动关闭广播频道。

示例

支持: false

请在至少两个Tab中打开此页面

你的浏览器不支持广播频道 Web API。

使用方法

BroadcastChannel 接口表示一个命名的频道,同一来源的任何浏览上下文都可以订阅它。它允许不同文档 (在不同窗口、选项卡、框架或 iframe 中) 之间进行通信。

消息通过在所有监听频道的 BroadcastChannel 对象上触发的消息事件进行广播。

ts
import { 
useBroadcastChannel
} from '@vueuse/core'
import {
shallowRef
} from 'vue'
const {
isSupported
,
channel
,
post
,
close
,
error
,
isClosed
,
} =
useBroadcastChannel
({
name
: 'vueuse-demo-channel' })
const
message
=
shallowRef
('')
message
.
value
= 'Hello, VueUse World!'
// 将消息发布到广播频道:
post
(
message
.
value
)
// 关闭频道:
close
()

类型声明

ts
export interface UseBroadcastChannelOptions extends ConfigurableWindow {
  /**
   * 频道的名称。
   */
  
name
: string
} /** * 响应式频道广播 * * @see https://vueuse.org/useBroadcastChannel * @see https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel * @param options * */ export declare function
useBroadcastChannel
<
D
,
P
>(
options
: UseBroadcastChannelOptions,
):
UseBroadcastChannelReturn
<
D
,
P
>
export interface
UseBroadcastChannelReturn
<
D
,
P
> {
isSupported
:
ComputedRef
<boolean>
channel
:
Ref
<BroadcastChannel | undefined>
data
:
Ref
<
D
>
post
: (
data
:
P
) => void
close
: () => void
error
:
ShallowRef
<Event | null>
isClosed
:
ShallowRef
<boolean>
}

源码

源码演示文档

贡献者

一纸忘忧
Anthony Fu
IlyaL
丶远方
Jelf
SerKo
Fernando Fernández
Alex Liu
Anthony Fu
Captain
Michael J. Roberts

更新日志

c6c6e - feat: use useEventListener where it was not being used (#4479)
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)