Skip to content

useBroadcastChannel

类别
导出体积
476 B
上次更改
2 minutes ago

响应式 BroadcastChannel API

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

示例

支持: false

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

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

使用方法

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

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

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

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

源码

源码演示文档

贡献者

Anthony Fu
一纸忘忧
丶远方
Jelf
Anthony Fu
Captain
Michael J. Roberts

更新日志

没有最近的更新日志