Server-sent events发送请求
策略类型
use hook
在使用扩展 hooks 前,确保你已熟悉了 alova 的基本使用。
通过 Server-sent Events(SSE)请求,内部使用EventSource实现。
注意
你不可以在使用 useSSE 时添加自定义 header,因为该标准不包含这一行为。
特性
- 更加简洁易用的使用方式;
- 自动管理连接;
安装
- vue
- react
- svelte
# npm
npm install @alova/scene-vue --save
# yarn
yarn add @alova/scene-vue
# npm
npm install @alova/scene-react --save
# yarn
yarn add @alova/scene-react
# npm
npm install @alova/scene-svelte --save
# yarn
yarn add @alova/scene-svelte
用法
- vue
- react
- svelte
import { useSSE } from '@alova/scene-vue';
const method = (value: string) => alova.Get('/api/source', { param: { key: value } });
const { data, eventSource, readyState, onMessage, onError, on, send, close } = useSSE(method, {
initialData: 'initial-data' // 初始时 data 中的数据
});
// connect
send('value');
console.log(data.value); // data 在接收到事件后更新,默认是 initialData
// 对应 eventsource 的 message 事件
const unbindMessage = onMessage(({ data }) => {
console.log(data);
});
const unbindError = onError(({ error }) => {
console.error('sse error', error);
close();
});
// 在需要的时候解绑
unbindMessage();
unbindError();
import { useSSE } from '@alova/scene-react';
const method = (value: string) => alova.Get('/api/source', { param: { key: value } });
const { data, eventSource, readyState, onMessage, onError, on, send, close } = useSSE(method, {
initialData: 'initial-data' // 初始时 data 中的数据
});
// connect
send('value');
console.log(data); // data 在接收到事件后更新,默认是 initialData
// 对应 eventsource 的 message 事件
const unbindMessage = onMessage(({ data }) => {
console.log(data);
});
const unbindError = onError(({ error }) => {
console.error('sse error', error);
close();
});
// 在需要的时候解绑
unbindMessage();
unbindError();
import { useSSE } from '@alova/scene-svelte';
const method = (value: string) => alova.Get('/api/source', { param: { key: value } });
const { data, eventSource, readyState, onMessage, onError, on, send, close } = useSSE(method, {
initialData: 'initial-data' // 初始时 data 中的数据
});
// connect
send('value');
console.log(data); // data 在接收到事件后更新,默认是 initialData
// 对应 eventsource 的 message 事件
const unbindMessage = onMessage(({ data }) => {
console.log(data);
});
const unbindError = onError(({ error }) => {
console.error('sse error', error);
close();
});
// 在需要的时候解绑
unbindMessage();
unbindError();
注意
useSSE 目前只能连接到一个源。也就是说,当试图连接多个目标时,上一个连接总会被断开。
const { data, eventSource, readyState, onMessage, onError, on, send, close } = useSSE(method);
send('value1');
send('value2'); // 这会断开上一个连接
send('value3'); // 这也会断开上一个连接
默认情况下,不会发送请求。当然,通过设置immediate = true