Skip to content

useBroadcastChannel

Category
Export Size
476 B
Last Changed
last year

响应式 BroadcastChannel API

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

Demo

支持: true

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

使用方法

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

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

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(message.value)

// 关闭频道:
close()

类型声明

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

Source

SourceDemoDocs

贡献者

Anthony Fu
丶远方
Jelf
Captain
Michael J. Roberts

变更日志

No recent changes

Released under the MIT License.

Build faster with AI
New Masterclass to help you leverage AI in your Vue workflow.
Get Early Access