Skip to content

useBroadcastChannel

反应式 广播通道 API

¥Reactive BroadcastChannel API.

自动关闭已卸载组件的广播通道。

¥Closes a broadcast channel automatically component unmounted.

示例

Supported: false

Please open this page in at least two tabs

Aww, snap! The Broadcast Channel Web API is not supported in your browser.

用法

¥Usage

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

¥The BroadcastChannel interface represents a named channel that any browsing context of a given origin can subscribe to. It allows communication between different documents (in different windows, tabs, frames, or iframes) of the same origin.

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

¥Messages are broadcasted via a message event fired at all BroadcastChannel objects listening to the channel.

js
import { ref } from 'vue'
import { useBroadcastChannel } from '@vueuse/core'

const {
  isSupported,
  channel,
  post,
  close,
  error,
  isClosed,
} = useBroadcastChannel({ name: 'vueuse-demo-channel' })

const message = ref('')

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/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: Ref<boolean>
  channel: Ref<BroadcastChannel | undefined>
  data: Ref<D>
  post: (data: P) => void
  close: () => void
  error: Ref<Event | null>
  isClosed: Ref<boolean>
}

源代码

源代码示例文档

变更日志

No recent changes

VueUse 中文网 - 粤ICP备13048890号