axios中断请求cancelToken

2020-10-21  本文已影响0人  贝斯特大师

axios的config中提供了一个cancelToken的属性来取消请求,在vue-cli中,使用cancelToken来取消请求。

const CANCEL_TOKEN = axios.CancelToken;
/**
* vue添加原型属性,记录请求信息
*/
Vue.prototype.$httpRequestList = [];
axios({
    url: url,
    methods: 'POST',
    data: options,
    cancelToken: new CANCEL_TOKEN(c => { //强行中断请求要用到的,记录请求信息
        Vue.prototype.$httpRequestList.push(c);
      })
}).then(res => {}).catch(err => {
  if (err.message == "interrupt") {
       console.log('已中断请求');
        return;
      }
})
/**
* 在路由切换之前检测来中断上个页面的请求
*/
router.beforeEach((to, from, next) => {   //路由切换检测是否强行中断,
  if(Vue.$httpRequestList.length>0){        //强行中断时才向下执行
      Vue.$httpRequestList.forEach(item=>{
          item('interrupt');//给个标志,中断请求
      })
  }
  next();
});
上一篇 下一篇

猜你喜欢

热点阅读