Vue切换页面时中断axios请求

需求分析

  • 当切换页面时,由于上一页面请求执行时间长,切换到该页面时,还未执行完,这时那个请求仍会继续执行直到请求结束,此时将会影响页面性能,并且可能对现在页面的数据显示造成一定影响,所以我们应该,切换页面前中断前面所有请求。
  • 在项目中经常有一些场景会连续发送多个请求,而异步会导致最后得到的结果不是我们想要的,并且对性能也有非常大的影响。例如一个搜索框,每输入一个字符都要发送一次请求,但输入过快的时候其实前面的请求并没有必要真的发送出去,这时候就需要在发送新请求的时候直接取消上一次请求。

具体操作

  • 在main.js里写一个全局httpRequestList的空数组,用来装我们的cancel函数:
//  cancelToken中的cancel函数
Vue.$httpRequestList=[];
  • 在封装的Axios请求里面,将cancel函数推入httpRequestList数组:

Axios 提供了一个 CancelToken的函数,这是一个构造函数,该函数的作用就是用来取消接口请求的。

// 在请求拦截器里面 统一添加 取消请求
request.interceptors.request.use(config => {
  // 强行中断请求要用到的,记录请求信息
  config['cancelToken'] = new CancelToken(function executor(cancel) {
      Vue.$httpRequestList.push(cancel) //存储cancle
  })
  config.headers = { ...config.headers, ...config.config.headers }
  ... ... 
  return config;
});

// response拦截器
// 在响应拦截器里面 统一添加 处理取消请求
request.interceptors.response.use(response => {
  ... ...
}, error => {
  if(error.message === 'interrupt') {
    console.log('请求中断');
    return new Promise(() => {});
  }
  // Vue.$httpRequestList = [];
  return Promise.reject(error)
});
  • 在路由守卫中,写一个执行cancel方法的clearHttpRequestingList方法,在每次跳转之前执行clearHttpRequestingList()函数
/**
* 在路由切换之前检测来中断上个页面的请求
*/
router.beforeEach((to, from, next) => { 
  clearHttpRequestingList();
  next();
});

// 清空cancelToken中的cancel函数
function clearHttpRequestingList() {
  // 路由切换检测是否强行中断, 强行中断时才向下执行
  if (Vue.$httpRequestList.length > 0) {
    Vue.$httpRequestList.forEach((item) => {
      // 给个标志,中断请求
      item('interrupt');
    })
    Vue.$httpRequestList = [];
  }
}

vuex管理使用

export default createStore({
  state: {
    httpRequestList: [],
  },
  mutations: {
    addHttpRequestList(state, payload) {
      if (payload == 0) {
        //强行中断时才向下执行
        state.httpRequestList.forEach(item => {
          item("interrupt"); //给个标志,中断请求
        });
        state.httpRequestList = [];
      } else {
        state.httpRequestList.push(payload);
      }
    },
  },
  actions: {
    async removeHttpRequestList(ctx) {
      ctx.commit("addHttpRequestList", 0);
    },
  },
  modules: {},
});
import store from '@/store';
// 在请求拦截器里面 统一添加 取消请求
request.interceptors.request.use(config => {
  // 请求配置
  config.cancelToken = new CancelToken(c => {
    //强行中断请求要用到的
    store.commit("addHttpRequestList", c);
  });
  ... ... 
  return config;
});
import store from '@/store';
// 调用
router.beforeEach((to, from, next) => { 
 store.dispatch('removeHttpRequestList');
  next();
});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值