vue实现切换路由菜单终止上个页面未完成的所有请求

3,374 阅读1分钟

场景

当切换路由页面后,上个页面的请求应该终止,实际跳转路由后network中添加新的请求, 上个页面的请求还是存在的会一直pending, 直到该请求加载成功或超时才肯罢休。

思路

利用axios拦截器(interceptors)和取消请求(cancelToken)

在axios 拦截器封装的js中把请求放置于全局变量的数组中, 可以挂在window对象上 或使用vuex来管理,在路由全局前置守卫中取消数组中的所有请求

解决方法

  1. request请求拦截器
window.axiosPromiseArr = [] // axios中设置放置要取消的对象
axios.interceptors.request.use(config => {
  //发起请求时保存页面所有请求
  config.cancelToken = new axios.CancelToken(cancel => {
    window.axiosPromiseArr.push({ cancel })
  });
  return config
});
  1. response响应拦截
axios.interceptors.response.use(res=>{
  //事件处理
  },error=>{
    if (axios.isCancel(error)) {
      // 为了终结promise链 (实际请求不会走到.catch(rej=>{}),这样就不会触发错误提示之类的)
      return new Promise(() => {});     
    }else{
      return Promise.reject(error)
    }
});
  1. 进入路由钩子拦截时候,取消保存的axiosPromiseArr
router.beforeEach((to, from, next) => {
  window._axiosPromiseArr.forEach((ele,index) => {
    ele.cancel() // 路由跳转之前,终止上一个页面正在请求的内容
    // 清空请求的参数
    delete window._axiosPromiseArr[index]
  });
});