feat(demo->useRequest): 更新错误重试示例 (#3456)

This commit is contained in:
luocong2016 2023-12-25 14:31:11 +08:00 committed by GitHub
parent 75f5b7ac4d
commit 7fa2578e6d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 69 additions and 4 deletions

View File

@ -1,13 +1,78 @@
<template>
<div class="m-10">
<a-button @click="handleClick" type="primary"> 点击会重新发起请求5次 </a-button>
<p class="mt-4">打开浏览器的network面板可以看到发出了六次请求</p>
</div>
<PageWrapper title="错误重试">
<Row :gutter="16">
<Col :span="8">
<Card title="Axios 错误重试">
<a-button @click="handleClick" type="primary"> 点击会重新发起请求5次 </a-button>
<div class="mt-4">打开浏览器的 network 面板可以看到发出了六次请求</div>
</Card>
</Col>
<Col :span="8">
<Card title="hooks 错误重试">
<Space>
<a-button @click="restRun" type="primary" :disabled="loading">
使用 hooks 发起重试
</a-button>
<a-button @click="restCancel">取消</a-button>
</Space>
<div class="mt-4"
>错误重试retryInterval 如果不设置默认采用简易的指数退避算法 1000 * 2 **
retryCount也就是第一次重试等待 2s第二次重试等待 4s以此类推如果大于 30s则取 30s
</div>
</Card>
</Col>
</Row>
</PageWrapper>
</template>
<script lang="ts" setup>
import { PageWrapper } from '@/components/Page';
import { useRequest } from '@vben/hooks';
import { testRetry } from '@/api/sys/user';
import { Card, Col, Row, Space, message } from 'ant-design-vue';
// @ts-ignore
const handleClick = async () => {
await testRetry();
};
function apiError() {
return new Promise<void>((resolve, reject) => {
setTimeout(() => {
reject(`TimeError: ${Date.now()}`);
}, 1300);
});
}
// PS >> useRequest API(: axios)使
// 使 API
// useRequest
// loading
// eg. restRunrestCancel
let i = 0;
const { loading, run, cancel } = useRequest(apiError, {
manual: true,
retryCount: 5,
// retryInterval: undefined, //
onError(error) {
if (i === 0) {
message.error(`发现错误`);
i++;
}
const now = Date.now();
message.error(`${i++} 次重试, Time:${now}`);
console.log(`Time: ${now}, Error: ${error}`);
},
});
const restRun = () => {
i = 0;
run();
};
const restCancel = () => {
i = 0;
cancel();
message.info('已取消');
};
</script>