Skip to content
On this page

useEventSource

使用EventSourceServer-Sent-Events 实例会对 HTTP 服务开启一个持久化的连接,以 text/event-stream 格式发送事件。

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')
import { useEventSource } from '@vueuse/core'

const { status, data, error, close } = useEventSource('https://event-source-url')
状态类型描述
statusRef<string>表示连接状态的只读值。可能的值为 CONNECTING (0)、OPEN (1) 或 CLOSED (2)
dataRef<string | null>引用通过 EventSource 接收到的最新数据,可以观察以响应传入的消息
eventSourceRef<EventSource | null>引用当前 EventSource 实例
方法签名描述
close() => void关闭 EventSource 连接。

Type Declarations

typescript
export type UseEventSourceOptions = EventSourceInit
/**
 * Reactive wrapper for EventSource.
 *
 * @see https://vueuse.org/useEventSource
 * @see  https://developer.mozilla.org/zh-CN/docs/Web/API/EventSource/EventSource EventSource
 * @param url
 * @param events
 * @param options
 */
export declare function useEventSource(
  url: string,
  events?: Array<string>,
  options?: UseEventSourceOptions
): {
  eventSource: Ref<EventSource | null>
  event: Ref<string | null>
  data: Ref<string | null>
  status: Ref<"OPEN" | "CONNECTING" | "CLOSED">
  error: Ref<Event | null>
  close: () => void
}
export type UseEventSourceReturn = ReturnType<typeof useEventSource>
export type UseEventSourceOptions = EventSourceInit
/**
 * Reactive wrapper for EventSource.
 *
 * @see https://vueuse.org/useEventSource
 * @see  https://developer.mozilla.org/zh-CN/docs/Web/API/EventSource/EventSource EventSource
 * @param url
 * @param events
 * @param options
 */
export declare function useEventSource(
  url: string,
  events?: Array<string>,
  options?: UseEventSourceOptions
): {
  eventSource: Ref<EventSource | null>
  event: Ref<string | null>
  data: Ref<string | null>
  status: Ref<"OPEN" | "CONNECTING" | "CLOSED">
  error: Ref<Event | null>
  close: () => void
}
export type UseEventSourceReturn = ReturnType<typeof useEventSource>

Source

Category
Export Size
1.21 kB
Last Changed
18 hours ago

SourceDocs

贡献者(Contributors)

日志(Changelog)

No recent changes

Released under the MIT License.