跳到主要内容

useBroadcastChannel

分类
导出大小
917 B
上次更改
8 个月前

响应式的 BroadcastChannel API

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

演示

支持:

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

啊哦,Broadcast Channel Web API 在您的浏览器中不受支持。

用法

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

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

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 the message to the broadcast channel:
post
(
message
.
value
)
// Option to close the channel if you wish:
close
()

类型声明

ts
export interface UseBroadcastChannelOptions extends ConfigurableWindow {
  /**
   * The name of the channel.
   */
  
name
: string
} /** * Reactive BroadcastChannel * * @see https://vueuse.org.cn/useBroadcastChannel * @see https://mdn.org.cn/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

更新日志

v12.5.0
c6c6e - feat: 在未使用 useEventListener 的地方使用它 (#4479)
0a9ed - feat!: 放弃对 Vue 2 的支持,优化打包并清理 (#4349)

根据 MIT 许可证发布。