Axios解决方案
import { ElLoading } from "element-plus";
// 其他自己的代码省略
// const instance = axios.create({
// baseURL: "/api",
// timeout: 10000, // 请求超时时间
// });
// 定义计数和定时器
let loadingTimer: NodeJS.Timeout | null = null;
let timerCount: number = 0;
// 请求拦截器
instance.interceptors.request.use(
(config: InternalAxiosRequestConfig) => {
timerCount++; // 每次请求++
return config;
},
(error) => {
return Promise.reject(error);
}
);
// 响应拦截器
instance.interceptors.response.use(
(response: AxiosResponse): any => {
timerCount--; // 每次请求--
return response.data;
},
(error) => {
timerCount--;
return Promise.reject(error);
}
);
// 加载loading。其他请求方法自行写
const loadingInstance =
ElLoading.service({
lock: true,
fullscreen: true,
})
请求完毕的回调函数判断关闭loading、而不是请求完一次就关闭一次。关键解决代码:
if (loadingTimer) {
clearTimeout(loadingTimer);
}
loadingTimer = setTimeout(() => {
if (timerCount === 0) {
loadingInstance?.close();
}
}, 300); // 300毫秒同时请求的间隔关闭时间
其他解决方案自行研究,这里只做参考,大部分会封装在axios。
感谢你的阅读,如对你有帮助请收藏+关注!
只分享干货实战和精品,从不啰嗦!!!
如某处不对请留言评论,欢迎指正~
博主可收徒、常玩QQ飞车,可一起来玩玩鸭~