重试
使用方式
typescript
import useRequest from '@pluve/use-request-vue';
const { data, loading, error } = useRequest(
() => fetch('/api/unstable-endpoint').then(res => {
if (!res.ok) throw new Error('请求失败');
return res.json();
}),
{
retryCount: 3, // 最多重 }
);配置
retryCount
- 类型:
number - 默认值:
0(不重试 - 说明 - 请求失败后的重试次数- 设置
-1表示无限重试(不推荐
- 设置
retryInterval
- 类型:
number - 默认值:
1000秒) - 说明 - 重试间隔时间(毫秒)
- 可以使用函数动态计算重试间
方法
cancel
- 说明 - 取消重试
基本使用
vue
<template>
<div>
<button @click="run">获取数据</button>
<div v-if="loading">加载..{{ retryCount ? `(${retryCount} 次重` : '' }}</div>
<div v-else-if="error">
错误: {{ error.message }}
<button @click="run">重试</button>
</div>
<div v-else>{{ data }}</div>
</div>
</template>
<script setup>
import useRequest from '@pluve/use-request-vue';
const { data, loading, error, run, retryCount } = useRequest(
() =>
fetch('/api/unstable').then((res) => {
if (Math.random() > 0.5) {
throw new Error('随机错误');
}
return res.json();
}),
{
manual: true,
retryCount: 3,
},
);
</script>指数退
typescript
const { data } = useRequest(
() =>
fetch('/api/unstable').then((res) => {
if (!res.ok) throw new Error('请求失败');
return res.json();
}),
{
retryCount: 5,
retryInterval: 5000,
},
);