コンテンツにスキップ

useEventSource

カテゴリ
エクスポートサイズ
679 B
最終更新
先週

EventSource または Server-Sent-Events インスタンスは、テキスト/event-stream形式でイベントを送信する HTTP サーバーへの永続的な接続を開きます。

使用法

js
import { useEventSource } from '@vueuse/core'

const { status, data, error, close } = useEventSource('https://event-source-url')

より多くのオプションについては、型宣言を参照してください。

名前付きイベント

2番目のパラメーターで名前付きイベントを定義できます

ts
import { useEventSource } from '@vueuse/core'

const { event, data } = useEventSource('https://event-source-url', ['notice', 'update'] as const)
js
import { useEventSource } from '@vueuse/core'
const { event, data } = useEventSource('https://event-source-url', [
  'notice',
  'update',
])

即時

自動接続(デフォルトで有効)。

これにより、open() が自動的に呼び出されるため、自分で呼び出す必要はありません。

url が ref として提供されている場合、その値が変更されたときに接続が再確立されるかどうか(または変更を有効にするために再度 open() を呼び出す必要があるかどうか)も制御します。

自動再接続

エラー時に自動的に再接続します(デフォルトでは無効)。

js
const { status, data, close } = useEventSource('https://event-source-url', [], {
  autoReconnect: true,
})

または、その動作をより詳細に制御します

js
const { status, data, close } = useEventSource('https://event-source-url', [], {
  autoReconnect: {
    retries: 3,
    delay: 1000,
    onFailed() {
      alert('Failed to connect EventSource after 3 retries')
    },
  },
})

型宣言

型宣言を表示
typescript
export type EventSourceStatus = "CONNECTING" | "OPEN" | "CLOSED"
export interface UseEventSourceOptions extends EventSourceInit {
  /**
   * Enabled auto reconnect
   *
   * @default false
   */
  autoReconnect?:
    | boolean
    | {
        /**
         * Maximum retry times.
         *
         * Or you can pass a predicate function (which returns true if you want to retry).
         *
         * @default -1
         */
        retries?: number | (() => boolean)
        /**
         * Delay for reconnect, in milliseconds
         *
         * @default 1000
         */
        delay?: number
        /**
         * On maximum retry times reached.
         */
        onFailed?: Fn
      }
  /**
   * Automatically open a connection
   *
   * @default true
   */
  immediate?: boolean
}
export interface UseEventSourceReturn<Events extends string[]> {
  /**
   * Reference to the latest data received via the EventSource,
   * can be watched to respond to incoming messages
   */
  data: Ref<string | null>
  /**
   * The current state of the connection, can be only one of:
   * 'CONNECTING', 'OPEN' 'CLOSED'
   */
  status: Ref<EventSourceStatus>
  /**
   * The latest named event
   */
  event: Ref<Events[number] | null>
  /**
   * The current error
   */
  error: Ref<Event | null>
  /**
   * Closes the EventSource connection gracefully.
   */
  close: EventSource["close"]
  /**
   * Reopen the EventSource connection.
   * If there the current one is active, will close it before opening a new one.
   */
  open: Fn
  /**
   * Reference to the current EventSource instance.
   */
  eventSource: Ref<EventSource | null>
  /**
   * The last event ID string, for server-sent events.
   * @see https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent/lastEventId
   */
  lastEventId: Ref<string | null>
}
/**
 * Reactive wrapper for EventSource.
 *
 * @see https://vueuse.dokyumento.jp/useEventSource
 * @see https://developer.mozilla.org/en-US/docs/Web/API/EventSource/EventSource EventSource
 * @param url
 * @param events
 * @param options
 */
export declare function useEventSource<Events extends string[]>(
  url: MaybeRefOrGetter<string | URL | undefined>,
  events?: Events,
  options?: UseEventSourceOptions,
): UseEventSourceReturn<Events>

ソース

ソースドキュメント

貢献者

Anthony Fu
Anthony Fu
Antério Vieira
Tycho
陪我去看海吧
schelmo
Michael J. Roberts
丶远方
Jelf
Shinigami
江麻妞
Shinigami
Alex Kozack
Johnson Chen
Charles

変更履歴

v12.0.0-beta.1 2024/11/21
0a9ed - feat!: Vue 2 のサポートを削除、バンドルを最適化、クリーンアップ (#4349)
v10.10.0 2024/5/27
29bc6 - feat: lastEventId を返す (#3984)
v10.8.0 2024/2/20
b33ab - 機能: オプションにautoReconnectimmediateを追加、型定義を更新 (#3793)
v10.1.1 2023/5/1 にリリース
790bc - 機能: url引数にオプションでstring | URL型を許可 (#3035)

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