跳到主要内容

useEventSource

分类
导出大小
1.12 kB
上次更改
2 个月前

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

用法

ts
import { 
useEventSource
} from '@vueuse/core'
const {
status
,
data
,
error
,
close
} =
useEventSource
('https://event-source-url')

更多选项请参阅类型声明

命名事件

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

ts
const { 
event
,
data
} =
useEventSource
(
'https://event-source-url', ['notice', 'update'] )

immediate

默认启用。

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

autoConnect

默认启用。

如果 url 以 ref 形式提供,当 url 改变时,它将自动重新连接到新的 url。

错误时自动重连

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

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

或者通过更多控制其行为的方式

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

数据序列化

使用序列化函数对传入数据应用自定义转换。

ts
const { 
data
} =
useEventSource
(
'https://event-source-url', [], {
serializer
: {
read
:
rawData
=>
JSON
.
parse
(
rawData
),
}, } ) // If server sends: '{"name":"John","age":30}' // data.value will be: { name: 'John', age: 30 }

类型声明

显示类型声明
ts
export type 
EventSourceStatus
= "CONNECTING" | "OPEN" | "CLOSED"
export interface
UseEventSourceOptions
<
Data
> 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
/** * Custom data serialization */
serializer
?: {
read
: (
v
?: string) =>
Data
} } 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
| null>
/** * 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://mdn.org.cn/en-US/docs/Web/API/MessageEvent/lastEventId */
lastEventId
:
ShallowRef
<string | null>
} /** * Reactive wrapper for EventSource. * * @see https://vueuse.org.cn/useEventSource * @see https://mdn.org.cn/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
<
Data
>,
):
UseEventSourceReturn
<
Events
,
Data
>

来源

源码文档

贡献者

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

更新日志

v13.8.0
64651 - feat: 添加 serializer (#4953)
v13.4.0
f6f0b - feat: 为命名事件添加 lastEventId (#4791)
v13.2.0
a969e - fix: 修复缺失的数据泛型 (#4726)
v12.8.1
79fcb - fix: 移除 readonly 以避免破坏性更改 (#4645)
v12.8.0
7432f - feat(types): 废弃 MaybeRefMaybeRefOrGetter,转而使用 Vue 的原生类型 (#4636)
v12.5.0
eddbf - feat: 更多被动事件处理程序 (#4484)
230f8 - feat: 新增 autoConnect 选项以与 useWebSocket 对齐 (#4204)
0a9ed - feat!: 放弃对 Vue 2 的支持,优化打包并清理 (#4349)
29bc6 - feat: 返回 lastEventId (#3984)
v10.8.0
b33ab - feat: 添加 autoReconnectimmediate 到选项中,更新类型定义 (#3793)
v10.1.1
790bc - feat: 允许 url 参数的类型为可选的 string | URL (#3035)

根据 MIT 许可证发布。