vue axios路由跳转取消所有请求 和 防止重复请求

直接上干货

在发送第二次请求的时候如果第一次请求还未返回,则取消第一次请求,以保证后发送的请求返回的数据不会被先发送的请求覆盖。

或者是跳转路由的时候取消还未返回的请求

第一步: axios 怎么取消:

const CancelToken = axios.CancelToken;
let cancel;
axios.get('/user/12345', {
cancelToken: new CancelToken(function executor(c) {
// An executor function receives a cancel function as a parameter
cancel = c;
})
});

第二步: 这是取消一个axios 如果是多个呢?那么我们就需要有个地方给存下来
vuex
state: {
// axios取消请求
axiosPromiseCancel: [],
}
第三步: axios 拦截器axios.js
import store from './store';
const CancelToken = axios.CancelToken;

let cancel;
// 防止重复请求
let removePending = (config) => {
for (let k in store.state['axiosPromiseCancel']) {
if (store.state['axiosPromiseCancel'][k].u === config.url + '&' + config.method) { //当前请求在数组中存在时执行函数体
store.state['axiosPromiseCancel'][k].f(); //执行取消操作
store.state['axiosPromiseCancel'].splice(k, 1); //把这条记录从数组中移除
}
}
};
axios.interceptors.request.use(config=>{
// 这个是 取消重点
removePending(config);
config.cancelToken = new CancelToken((cancel) => {
store.state['axiosPromiseCancel'].push({ u: config.url + '&' + config.method, f: cancel });
});
  return config;
});
axios.interceptors.response.use(res=>{
removePending(res.config);
  // do something...
},error=>{
if (axios.isCancel(error)) {
// 为了终结promise链 就是实际请求 不会走到.catch(rej=>{});这样就不会触发错误提示之类了。
return new Promise(() => {});
}else{
return Promise.reject(error)
}});

第四步: 就是在router 里做取消动作了 router.js

import store from './store';
router.beforeEach((to, from, next) => {
if(store.state['axiosPromiseCancel'].length > 0) {
store.state['axiosPromiseCancel'].forEach(e => {
e && e.f()
});
}
store.state['axiosPromiseCancel'] = [];

})
原文地址:https://www.cnblogs.com/zhaofeis/p/11422777.html