Vue使用axios,終止多次請求方式,防抖
三種防抖策略:
- 定時器;
- abort();
- axios自帶撤銷請求
這裏只說第三種的使用步驟~
1.首先在methods中添加方法:
methods: {
cancelRequest(){
if(typeof this.source ==='function'){
this.source('終止請求')
}
}
}
2.在請求開始前緩存this,並且調用上面方法,取消請求
var that = this;
this.cancelRequest();
3.請求時給axios傳入第二個參數;
this.axios.get('請求路徑', {
cancelToken: new this.axios.CancelToken(function(c) {
that.source = c;
})
}).then((res)=>{
//正常響應需要做的處理
}).catch((err) => {
if (that.axios.isCancel(err)) {
console.log('Rquest canceled', err.message); //請求如果被取消,這裏是返回取消的message
} else {
//handle error
console.log(err);
}
})
以上就完成了