コンテンツにスキップ

useBroadcastChannel

カテゴリ
エクスポートサイズ
476 バイト
最終変更日
先週

リアクティブな BroadcastChannel API です。

コンポーネントがアンマウントされると、ブロードキャストチャネルは自動的に閉じられます。

デモ

サポート: false

このページを少なくとも2つのタブで開いてください

おっと、Broadcast Channel Web APIはあなたのブラウザではサポートされていません。

使用方法

BroadcastChannelインターフェースは、指定されたオリジンの任意のブラウジングコンテキストがサブスクライブできる名前付きチャネルを表します。同じオリジンの異なるドキュメント(異なるウィンドウ、タブ、フレーム、またはiframe)間の通信を可能にします。

メッセージは、チャネルをリッスンしているすべてのBroadcastChannelオブジェクトで発生するmessageイベントを介してブロードキャストされます。

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 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.dokyumento.jp/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

変更履歴

v12.0.0-beta.1 2024/11/21
0a9ed - feat!: Vue 2のサポートを廃止し、バンドルを最適化し、クリーンアップ (#4349)

MITライセンスでリリースされています。