跳到内容

useBroadcastChannel

类别
导出大小
510 B
最近更改
3 周前

响应式 BroadcastChannel API

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

演示

支持: false

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

哎呀!您的浏览器不支持 Broadcast Channel Web API。

用法

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

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

js
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()

类型声明

typescript
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>
}

SourceDemoDocs

贡献者

Anthony Fu
IlyaL
丶远方
Jelf
Fernando Fernández
Alex Liu
Anthony Fu
Captain
Michael J. Roberts

更新日志

v12.5.0 于 1/22/2025
c6c6e - feat: 在未使用 useEventListener 的地方使用它 (#4479)
v12.0.0-beta.1 于 11/21/2024
0a9ed - feat!: 删除 Vue 2 支持,优化捆绑包并清理 (#4349)

在 MIT 许可证下发布。