主题
useEventSource
一个 EventSource 或 Server-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
ts
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
const { event, data } = useEventSource(
'https://event-source-url',
['notice', 'update']
)immediate
默认启用。
🌐 Enable by default.
调用可组合函数时立即建立连接。
🌐 Establish the connection immediately when the composable is called.
autoConnect
默认启用。
🌐 Enable by default.
如果 url 作为 ref 提供,则当 url 发生更改时,它会自动重新连接到新的 url。
🌐 If url is provided as a ref, when the url changes, it will automatically reconnect to the new url.
发生错误时自动重新连接
🌐 Auto Reconnection on Errors
出现错误时自动重新连接(默认禁用)。
🌐 Reconnect on errors automatically (disabled by default).
ts
const { status, data, close } = useEventSource(
'https://event-source-url',
[],
{
autoReconnect: true,
}
)或者对其行为进行更多控制:
🌐 Or with more controls over its behavior:
ts
const { status, data, close } = useEventSource(
'https://event-source-url',
[],
{
autoReconnect: {
retries: 3,
delay: 1000,
onFailed() {
alert('Failed to connect EventSource after 3 retries')
},
},
}
)数据序列化
🌐 Data Serialization
使用序列化函数对传入数据应用自定义转换。
🌐 Apply custom transformations to incoming data using a serialization function.
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 }