在项目中经常有一些场景会连续发送多个请求,而异步会导致最后得到的结果不是我们想要的,并且对性能也有非常大的影响。例如一个搜索框,每输入一个字符都要发送一次请求,但输入过快的时候其实前面的请求并没有必要真的发送出去,这时候就需要在发送新请求的时候直接取消上一次请求。
<script>
import axios from 'axios'
import qs from 'qs'
export default {
methods: {
request(keyword) {
var CancelToken = axios.CancelToken
var source = CancelToken.source()
// 取消上一次请求
this.cancelRequest();
// 有的人可能会出现415 400的错误,415是因为没有设置对Content-Type 400是因为使用了qs.stringify(), 可以修改成JSON.stringify() 试试
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>
这样就可以成功取消上一次请求啦!真的非常好用~ 亲测有效
2074

被折叠的 条评论
为什么被折叠?



