来回切换axios取消上一次请求,版本0.22

发布时间 2023-03-31 17:31:29作者: 漫漫长路

 

method的方法

 

getCateApi

 

 

 

async getCateApi(){
            // 用户快速切换的时候取消上一个请求,要不然太卡了
            const axiosSource = this.axios.CancelToken.source();
            this.cancelRequest = { cancel: axiosSource.cancel };
             await this.axios.post('/h5/categoriesZoneV/'+this.id,qs.stringify({
                field:this.field,
                type:this.type,
                page:this.page,
                perNum:this.perNum,
            }),{
                 cancelToken: axiosSource.token,
                 headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            }).then((response) => {
                // 10个10个添加进去
                response.data.data.forEach(item=>{
                    this.dataArray.push(item);
                })
                this.perNum+=1;
                if (this.dataArray.length >= response.data.total) {
                    this.finished = true;
                }
                 // if(this.dataArray.length==0){
                 //     this.empty=false;
                 //     this.finished = true;
                 // }
                console.log( this.dataArray)
                console.log(response.data.total,this.dataArray.length)
                console.log(response.data)

            }).catch(function (error){
                console.log(error,'err')
            });
        },

 

还有三个 cancel, logResponseErrors, clearOldRequest

cancel:function (){
            this.cancelRequest.cancel();
            this.clearOldRequest("Cancelled");
        },
        logResponseErrors(err) {
            if (this.axios.isCancel(err)) {
                console.log("Request cancelled");
            }
        },
        clearOldRequest(msg) {
            this.cancelRequest = null;
        },

 

 

 

 

 

data的定义

// 取消上一次请求
   cancelRequest: null,

 

 

 

使用

来回切换

 

 

 

 

 

 

效果