useEventSource
一个 EventSource 或 Server-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 作为引用,当 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')
},
},
})
类型声明
显示类型声明
typescript
export type EventSourceStatus = "CONNECTING" | "OPEN" | "CLOSED"
export interface UseEventSourceOptions extends EventSourceInit {
/**
* 启用自动重连
*
* @default false
*/
autoReconnect?:
| boolean
| {
/**
* 最大重试次数。
*
* 或者你可以传递一个断言函数(如果要重试,则返回true)。
*
* @default -1
*/
retries?: number | (() => boolean)
/**
* 重连延迟,单位为毫秒
*
* @default 1000
*/
delay?: number
/**
* 在达到最大重试次数时触发。
*/
onFailed?: Fn
}
/**
* 在调用这个可组合组件时立即打开连接
*
* @default true
*/
immediate?: boolean
/**
* 当 URL 改变时自动连接到 websocket
*
* @default true
*/
autoConnect?: boolean
}
export interface UseEventSourceReturn<Events extends string[], Data = any> {
/**
* 对通过 EventSource 接收到的最新数据的 ref,
* 可以被监视以响应传入的消息
*/
data: ShallowRef<Data>
/**
* 连接的当前状态,只能是以下之一:
* 'CONNECTING', 'OPEN', 'CLOSED'
*/
status: ShallowRef<EventSourceStatus>
/**
* 最新的命名事件
*/
event: ShallowRef<Events[number] | null>
/**
* 当前错误
*/
error: ShallowRef<Event | null>
/**
* 优雅地关闭 EventSource 连接。
*/
close: EventSource["close"]
/**
* 重新打开 EventSource 连接。
* 如果当前连接处于活动状态,则会在打开新连接之前关闭当前连接。
*/
open: Fn
/**
* 对当前 EventSource 实例的 ref。
*/
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>
}
/**
* 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>
源码
贡献者
更新日志
v12.8.1
on 3/5/2025v12.8.0
on 3/5/2025v12.5.0
on 1/22/2025v12.2.0-beta.1
on 12/23/2024v12.0.0-beta.1
on 11/21/2024v10.10.0
on 5/27/2024v10.8.0
on 2/20/2024v10.1.1
on 5/1/2023