cancelToken来取消请求(axios中断请求cancelToken)

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();
});

 

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: {},
});

/*调用*/
 store.dispatch('removeHttpRequestList');

/*请求配置*/
config.cancelToken = new CancelToken(c => {
    //强行中断请求要用到的
    store.commit("addHttpRequestList", c);
  });
本文《cancelToken来取消请求(axios中断请求cancelToken)》由网赚联盟( wangzhuan.org.cn )整理或原创,感谢您的阅读。

随机文章

站长导航
搜素引擎算法
关键词排名优化
SEO小小课堂网
SEO教程
站长导航
友情链接交换
搜素引擎算法

百度搜索“网赚联盟”即可找到本站,微信搜索“小小课堂网”关注小小课堂网公众号。网赚联盟( wangzhuan.org.cn )欢迎用户投稿,发布者:用户投稿,文章版权归作者所有,投稿文章不代表网赚联盟立场,中二少年发布为网赚联盟原创文章,转载请注明出处:https://wangzhuan.org.cn/126706.html