Skip to content

useEventSource

EventSource服务器发送的事件 实例打开与 HTTP 服务器的持久连接,该服务器以文本/事件流格式发送事件。

¥An EventSource or Server-Sent-Events instance opens a persistent connection to an HTTP server, which sends events in text/event-stream format.

用法

¥Usage

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

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

请参阅 类型声明 了解更多选项。

¥See the Type Declarations for more options.

命名事件

¥Named Events

你可以使用第二个参数定义命名事件

¥You can define named events with the second parameter

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',
])

即时

¥Immediate

自动连接(默认启用)。

¥Auto-connect (enabled by default).

这会自动为你调用 open(),你不需要自己调用它。

¥This will call open() automatically for you and you don't need to call it by yourself.

如果 url 作为 ref 提供,这还控制当其值更改时是否重新建立连接(或者是否需要再次调用 open() 以使更改生效)。

¥If url is provided as a ref, this also controls whether a connection is re-established when its value is changed (or whether you need to call open() again for the change to take effect).

自动重连

¥Auto-reconnection

出现错误时自动重新连接(默认禁用)。

¥Reconnect on errors automatically (disabled by default).

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

或者对其行为进行更多控制:

¥Or with more controls over its behavior:

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.org/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>

源代码

源代码文档

变更日志

No recent changes

VueUse 中文网 - 粤ICP备13048890号