// 删除重复请求
let s = 1; //单位秒,ajax取消延后时间
let pending = []; //声明一个数组用于存储每个请求的取消函数和axios标识
let cancelToken = Axios.CancelToken;
let removePending = config => {
pending = pending.filter(i => new Date().getTime() - i.t < 500); // 过滤n秒前发的请求
if (
pending.length > 1 &&
pending[pending.length - 2].u === config.url &&
pending[pending.length - 1].t - pending[pending.length - 2].t < s * 500
) {
// console.log('ajax取消操作');
pending[pending.length - 2].f(); //执行取消操作
pending.splice(pending.length - 2, 1);
}
};
请求拦截器内:
const CANCEL_RETRANSMIT = [] // 指定需判断重复请求的接口
axios.interceptors.request.use(
async config => {
...
// 删除重复请求
if (CANCEL_RETRANSMIT.indexOf(config.url) > -1) {
console.log(config);
config.cancelToken = new cancelToken(c => {
pending.push({
u: url,
t: new Date().getTime(),
f: c,
});
});
await removePending(config);
}
}
return config;
}