Vue使用AbortController取消请求

官方文档

https://github.com/axios/axios#cancellation

Cancellation
AbortController
Starting from v0.22.0 Axios supports AbortController to cancel requests in fetch API way:

const controller = new AbortController();

axios.get('/foo/bar', {
   signal: controller.signal
}).then(function(response) {
   //...
});
// cancel the request
controller.abort()

示例

场景

连续点击检索按钮,取最后一次检索结果,防止上次请求比此次请求慢,而覆盖此次检索结果的问题

依赖

"axios": "^0.22.0",

代码

// 检索接口 取消请求传入config

function getSearchSuggest(query,config) {
    return request.get(url,config);
}
// 初始化
abortController:new AbortController(),
// 检索
querySearch(str) {
			this.abortController.abort(); // 取消上次请求
			this.abortController = new AbortController(); // 新的请求
		        analyzeResponse({
				request: searchService.getSearchSuggest(str,{signal:this.abortController.signal}), // 请求传入config
				})
			.then(data => {
				/.....
			})
			.catch(err => console.error(err));
			}
		},
posted @ 2023-02-07 10:40  DurianTRY  阅读(379)  评论(0编辑  收藏  举报