当条件搜索时,快速频繁点击某一个搜索项,如果上一次的请求时间过长而下一次的请求时间较短时,上一次的请求结果将会覆盖下一次的请求数据,造成显示得结果数据不是我们预期的结果,影响用户使用。axios方法中提供了取消请求的接口:
axios详细介绍
封装axios情况:
api封装文件:
export const postCancleRequest = (url, params, that) => {
return axios({
method: 'post',
url: `${base}${url}`,
data: qs.stringify(params, {
indices: false
}),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
cancelToken: new axios.CancelToken(function executor(c) { // 设置 cancel token
that.source = c;
})
});
}
vue中methods使用:
_this:指向vue;
data(){
return {
source:null
}
},
methods:{
cancel(){
if(typeof this.source ==='function'){
this.source('终止请求'); //取消请求
}
},
getList() {
/*
* 条件改变,获取列表,滚动条清零
* 页码初始化
* */
this.cancel(); //在请求发出前取消上一次未完成的请求;
let para = { };
postCancleRequest(this.$globe.bpiURL + '/admin/ledger/queryCount', para,_this).then(res => {
// console.log(res.data)
if (res.data && res.data.code == '2000') {
}
}).catch(err=>{
if (this.$axios.isCancel(err)) {
console.log('Rquest canceled', err.message); //请求如果被取消,这里是返回取消的message
} else {
//handle error
console.log(err);
}
})
},
}