Vue 跳转路由时中断异步请求

使用导航守卫

在router/index.js中增加前置守卫:

router.beforeEach(function (to, from, next) {
  store.state.data.requests.forEach(xhr=>xhr.abort());//data是我的模块名
  store.state.data.requests =[];
  next();
});

在router中引入vuex

import store from ‘…/store/index’

进行异步请求时

  setOrderList({state,commit}){
    console.log("request order list..");
    let url = GET.Orders(state.user.userId);
    let xhr = _fetch(url);
    xhr.then(res=>res.json()).then(data=>{
      console.log("get order:",data);
      commit(SET_ORDER_LIST,data.data)
    }).catch(err=>{
      console.log("get order list failed! ",err)
    });
    state.requests.push(xhr);
  }

fetch需要重新封装


let _fetch = (function(fetch){
  return function(url,options){
    let abort = null;
    let abort_promise = new Promise((resolve, reject)=>{
      abort = () => {
        reject('abort.');
      };
    });
    let promise = Promise.race([
      fetch(url,options),
      abort_promise
    ]);
    promise.abort = abort;
    return promise;
  };
})(fetch);

注意:

Promise.race在第一个promise对象变为Fulfilled之后,并不会取消其他promise对象的执行。只是只有先完成的Promise才会被Promise.race后面的then处理。其它的Promise还是在执行的,只不过是不会进入到promise.race后面的then内。

所以,fetch的网络请求还是在继续,并不会中断!
为了中断请求,就不能使用fetch

参考链接:https://www.chuchur.com/article/vue-router-request-abort

你可能感兴趣的:(前端杂事)