美文网首页
axios中断请求cancelToken

axios中断请求cancelToken

作者: 贝斯特大师 | 来源:发表于2020-10-21 14:55 被阅读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();
});

相关文章

网友评论

      本文标题:axios中断请求cancelToken

      本文链接:https://www.haomeiwen.com/subject/yvxemktx.html