需要在axios配置里面加上以上代碼。
```
letpending=[];//聲明一個數組用于存儲每個ajax請求的取消函數和ajax標識
letcancelToken=axios.CancelToken;
letremovePending=(config)=>{
for(letpinpending) {
if(pending[p].u===config.url+'&'+config.method) {//當當前請求在數組中存在時執行函數體
pending[p].f();//執行取消操作
pending.splice(p,1);//把這條記錄從數組中移除
}
}
}
letcutReq=(config)=>{
for(letpinpending) {
if(pending[p].u===config.url+'&'+config.method) {//當當前請求在數組中存在時執行函數體
returntrue;
}
}
}
//添加請求攔截器
axios.interceptors.request.use(config=>{
letflag=cutReq(config);
if(flag===true)returnnull;//當上一次相同請求未完成時,無法進行第二次相同請求
config.cancelToken=newcancelToken((c)=>{
//這里的ajax標識我是用請求地址&請求方式拼接的字符串,當然你可以選擇其他的一些方式
pending.push({u:config.url+'&'+config.method,f:c});
});
returnconfig;
},error=>{
returnPromise.reject(error);
});
//添加響應攔截器
axios.interceptors.response.use(res=>{
removePending(res.config);//在一個ajax響應后再執行一下取消操作,把已經完成的請求從pending中移除
returnres;
},error=>{
return{data:{} };
});
```