前言:
在實際項目中,我們可能需要對請求進行“防抖”處理。這里主要是為了阻止用戶在某些情況下短時間內(nèi)重復(fù)點擊某個按鈕,導(dǎo)致前端向后端重復(fù)發(fā)送多次請求。這里我列舉兩種比較常見的實際情況:
1.PC端 - 用戶雙擊搜索按鈕,可能會觸發(fā)兩次搜索請求
2.移動端 - 因移動端沒有點擊延遲,所以極易造成誤操作或多操作,造成請求重發(fā)
核心——
- 在Axios中取消請求最核心的方法是CanelToken。在官網(wǎng)文檔中有寫到兩種方法使用CancelToken,這里簡單粘貼出來,并增加了注釋
方法1:
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
axios.get('/user/12345', {
// 必須對請求進行cancelToken設(shè)置
cancelToken: source.token
}).catch(function (thrown) {
// 如果請求被取消則進入該方法判斷
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// handle error
}
});
// 取消上面的請求
// source.cancel('messge') message為可選項,必須為String
source.cancel('Operation canceled by the user.');
方法2:
const CancelToken = axios.CancelToken;
let cancel;
axios.get('/user/12345', {
// 在options中直接創(chuàng)建一個cancelToken對象
cancelToken: new CancelToken(function executor(c) {
cancel = c;
})
});
// 取消上面的請求
cancel();
app項目中搜索功能請求的攔截
<script>
export default {
name : 'Search',
data(){
return {
message : '',
moviesList : []
}
},
methods : {
//首先在methods中定義cancelRequest()方法
cancelRequest(){
if(typeof this.source ==='function'){
this.source('終止請求')
}
}
},
//用watch去監(jiān)聽message輸入框
watch : {
message(newVal){
var that = this;
var cityId = this.$store.state.city.id;
this.cancelRequest();
this.axios.get('/api/searchList? cityId='+ cityId +'&kw='+newVal,{
cancelToken: new this.axios.CancelToken(function(c){
that.source = c;
})
}).then((res)=>{
var msg = res.data.msg;
var movies = res.data.data.movies;
if(msg && movies){
this.moviesList = res.data.data.movies.list;
}
}).catch((err) => {
if (this.axios.isCancel(err)) {
console.log('Rquest canceled', err.message); //請求如果被取消,這里是返回取消的message
} else {
//handle error
console.log(err);
}
});
}
}
}
</script>