Skip to content

useEventSource

Category
Export Size
1.02 kB
Last Changed
last month

EventSourceServer-Sent-Events 实例打开与 HTTP 服务器的持久连接,该服务器以 text/event-stream 格式发送事件。

用法

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

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

查看 类型声明 获取更多选项。

命名事件

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

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

默认启用。

在调用组合式函数时立即建立连接。

autoConnect

默认启用。

如果 url 作为 ref 提供,当 url 更改时,它将自动重新连接到新的 url。

错误时自动重连

在错误时自动重连(默认禁用)。

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('在 3 次重试后连接 EventSource 失败')
    },
  },
})

Type Declarations

Show Type Declarations
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
      }
  /**
   * Immediately open the connection when calling this composable
   *
   * @default true
   */
  immediate?: boolean
  /**
   * Automatically connect to the websocket when URL changes
   *
   * @default true
   */
  autoConnect?: boolean
}
export interface UseEventSourceReturn<Events extends string[], Data = any> {
  /**
   * Reference to the latest data received via the EventSource,
   * can be watched to respond to incoming messages
   */
  data: ShallowRef<Data>
  /**
   * The current state of the connection, can be only one of:
   * 'CONNECTING', 'OPEN' 'CLOSED'
   */
  status: ShallowRef<EventSourceStatus>
  /**
   * The latest named event
   */
  event: ShallowRef<Events[number] | null>
  /**
   * The current error
   */
  error: ShallowRef<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: ShallowRef<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[], Data = any>(
  url: MaybeRefOrGetter<string | URL | undefined>,
  events?: Events,
  options?: UseEventSourceOptions,
): UseEventSourceReturn<Events>

Source

SourceDocs

Contributors

Anthony Fu
丶远方
James Garbutt
Fernando Fernández
Anthony Fu
Antério Vieira
Robin
IlyaL
Tycho
陪我去看海吧
schelmo
Michael J. Roberts
Jelf
Shinigami
江麻妞
Shinigami
Alex Kozack
Johnson Chen
Charles

Changelog

79fcb - fix: remove readonly to not be breaking (#4645)
7432f - feat(types): deprecate MaybeRef and MaybeRefOrGetter in favor of Vue's native (#4636)
eddbf - feat: more passive event handlers (#4484)
230f8 - feat: new autoConnect option to align with useWebSocket (#4204)
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)
29bc6 - feat: return lastEventId (#3984)
b33ab - feat: add autoReconnect and immediate to options, update typings (#3793)
790bc - feat: allow optional string | URL type for url arg (#3035)

Released under the MIT License.