轮询
使用方式
typescript
import useRequest from '@pluve/use-request-vue';
const { data, cancel } = useRequest(() => fetch('/api/messages').then((res) => res.json()), {
pollingInterval: 3000, // 轮询间隔(毫秒)
});
// 取消轮询
// cancel();配置
pollingInterval
- 类型:
number - 必填:是
- 说明 - 轮询间隔时间(毫秒)
- 设置
0时停止轮
- 设置
pollingWhenHidden
- 类型:
boolean - 默认值:
true - 说明 - 当页面不可见时是否继续轮 - 如果
false,页面不可见时会暂停轮询,页面重新可见后恢复
方法
cancel
- 说明 - 取消轮询
示例
基本使用
vue
<template>
<div>
<h2>未读消息: {{ data?.count || 0 }}</h2>
<button @click="cancel">停止轮询</button>
<button @click="reload">重新开/button>
</div>
</template>
<script setup>
import useRequest from '@pluve/use-request-vue';
const { data, cancel, reload } = useRequest(
() => fetch('/api/unread-messages').then(res => res.json()),
{
pollingInterval: 5000, // 5秒轮询一 }
);
</script>页面不可见时暂停轮询
typescript
const { data } = useRequest(() => fetch('/api/notifications').then((res) => res.json()), {
pollingInterval: 10000, // 10秒轮询一
pollingWhenHidden: true, // 页面不可见时暂停轮询
});