一、前言
在項目中經常有一些場景會連續發送多個請求,而異步會導緻最後得到的結果不是我們想要的,并且對性能也有非常大的影響。例如一個搜尋框,每輸入一個字元都要發送一次請求,但輸入過快的時候其實前面的請求并沒有必要真的發送出去,這時候就需要在發送新請求的時候直接取消上一次請求。
二、代碼
<script>
import axios from 'axios'
import qs from 'qs'
export default {
methods: {
request(keyword) {
var CancelToken = axios.CancelToken
var source = CancelToken.source()
// 取消上一次請求
this.cancelRequest();
axios.post(url, qs.stringify({kw:keyword}), {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
},
cancelToken: new axios.CancelToken(function executor(c) {
that.source = c;
})
}).then((res) => {
// 在這裡處理得到的資料
...
}).catch((err) => {
if (axios.isCancel(err)) {
console.log('Rquest canceled', err.message); //請求如果被取消,這裡是傳回取消的message
} else {
//handle error
console.log(err);
}
})
},
cancelRequest(){
if(typeof this.source ==='function'){
this.source('終止請求')
}
},
}
}
</script>
三、結語
這樣就可以成功取消上一次請求啦!真的非常好用~
原文位址:
https://segmentfault.com/a/1190000016963943