axios取消上一次请求

项目需求:列表式切换商品,有时候上一次请求的结果非常慢,而我又点了另外一个商品,这时候第二次请求的接口比上一次快,那么就点击第二次的商品看到的信息却是上一次的商品信息,这样的用户体验极其不好;
解决方案:在点击下一个商品的时候,将上一个商品请求的接口中断取消请求。
axios官网给出了取消请求的方法:

方法一:
axios.get(’/user/12345’, {
cancelToken: axios.CancelToken.source().token
}).catch(function(thrown) {
if (axios.isCancel(thrown)) {
console.log(‘Request canceled’, thrown.message);
} else {
// handle error
}
});

axios.post(’/user/12345’, {
name: ‘new name’
}, {
cancelToken: axios.CancelToken.source().token
})

// cancel the request (the message parameter is optional)
source.cancel(‘Operation canceled by the user.’);

方法二:
let cancel;
axios.get(’/user/12345’, {
cancelToken: new axios.CancelToken(function executor© {
// An executor function receives a cancel function as a parameter
cancel = c;
})
});

// cancel the request
cancel();
1
2
3
4
5
6
7
8
9
10
11
根据项目需求给出解决方案:

vue:
data(){
return{
source: null, //存放取消的请求方法
}
},
methods:{
cancelQuest(){
if(typeof this.source ===‘function’){
this.source(‘终止请求’); //取消请求
}
},
getInfo(id){
const _this = this;
this.cancelQuest(); //在请求发出前取消上一次未完成的请求;
//发送请求
this.axios.get(/markets/tradeInfo/${id}?top=40,{
cancelToken: new this.axios.CancelToken(function executor© {
_this.source = c;
})
}).then(res =>{
//handle result
}).catch(error => {
if (this.axios.isCancel(err)) {
console.log(‘Rquest canceled’, err.message); //请求如果被取消,这里是返回取消的message
} else {
//handle error
console.log(err);
}
})
}
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值