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

取消Axios请求

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

第一步: 使用Axios取消请求

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

此处,我们使用axios的CancelToken来取消请求。

第二步: 存储多个取消的axios请求

state: {
  // 用于存储axios取消请求的数组
  axiosPromiseCancel: [],
}
    

通过Vuex的state,我们可以存储多个请求的取消函数。

第三步: 设置Axios拦截器

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);
}, error=>{
  if (axios.isCancel(error)) {
    return new Promise(() => {});
  } else {
    return Promise.reject(error);
  }
});
    

在此步骤中,我们设置axios的请求和响应拦截器,以处理和取消请求。

第四步: 在路由中取消请求

import store from './store';

router.before

posted on 2019-08-28 11:00  完美前端  阅读(4121)  评论(0)    收藏  举报

导航