Vue axios Interrupt Request - + repeat request switch pages

Interruption when switching pages

I. Overview

Vue single page in the development process, encountered such a situation, when I switch pages, due to previous page request execution for a long time, switch to that page, has not yet been performed, then the request will continue until the request end, this time will affect the performance of the page, and the page is now possible to display data some impact

So we should, before switching page breaks all previous requests

Second, the solution

In main.js, the reseal axios request, the trap request router.beforeEach

Vue.prototype.$http= axios;
//Vue函数添加一个原型属性$axios 指向axios,这样vue实例或组件中不用再去重复引用Axios 直接用this.$axios就能执行axios 方法
const CancelToken = axios.CancelToken;
Vue.$httpRequestList=[];

Vue.prototype.$ajax = (type, url, data) => {
    return new Promise((resolve, reject) => {   //封装ajax
        var aa = {
            method: type,
            url: url,
            cancelToken: new CancelToken(c => {  //强行中断请求要用到的
                Vue.$httpRequestList.push(c);
            })
        }
        var json = (type == 'get') ? Object.assign(aa, { params: data }) : Object.assign(aa, { data: data });
        var ajax = Vue.prototype.$http(json).then(res => {
            resolve(res);
        }).catch(error => {   //中断请求和请求出错的处理
                if (error.message == "interrupt") {
                    console.log('已中断请求');
                    return;
                } else {
                    reject(error);
                }
            })
        return ajax;
    })
};


router.beforeEach((to, from, next) => {   //路由切换检测是否强行中断,
    if(Vue.$httpRequestList.length>0){        //强行中断时才向下执行
        Vue.$httpRequestList.forEach(item=>{
            item('interrupt');//给个标志,中断请求
        })  
    }
    next();    
});

Use request

this.$axios('get',url,param).then(res=>{

}).catch(err=>{

});

Third, analyzing and interpreting

axios Chinese official website ( http://www.axios-js.com/zh-cn/docs/) to cancel description of token

Use cancel token cancellation request

A method using cancelToken.sourse factory methods to create a cancel token

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get('/user/12345', {
  cancelToken: source.token
}).catch(function(thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
     // 处理错误
  }
});
axios.post('/user/12345', {
  name: 'new name'
}, {
  cancelToken: source.token
})
// 取消请求(message 参数是可选的)
source.cancel('Operation canceled by the user.');

The second method by a transfer function executor to CancelTokencreate cancel token constructor:

const CancelToken = axios.CancelToken;
let cancel;

axios.get('/user/12345', {
  cancelToken: new CancelToken(function executor(c) {
    // executor 函数接收一个 cancel 函数作为参数
    cancel = c;
  })
});

// cancel the request
cancel();

Repeat interrupt request

instance.interceptors.request.use(config => {
    config.cancelToken = new CancelToken(c => { 
        if(hasKey(this.queue,url)) {
            c(url);
        }else{
            this.queue[url] = true;
        };
    })
    return config
}, error => {
    //return Promise.reject(error)
})

Guess you like

Origin www.cnblogs.com/ajaemp/p/11905901.html