使用 axios 和 vue.js 取消之前的请求 [英] Cancel previous request using axios with vue.js
本文介绍了使用 axios 和 vue.js 取消之前的请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 axios
和 vue.js
.我已经谷歌了它,并检查了 axios 文档,但仍然不明白如何去做.
解决方案
2020 更新:如何取消 axios 请求
生成一个cancelToken
并保存
从 'axios' 导入 axiosconst request = axios.CancelToken.source();
将 cancelToken
传递给 axios 请求
axios.get('API_URL', { cancelToken: request.token })
访问你存储的请求并调用.cancel()
方法取消它
request.cancel("可选消息");
<小时><小时><块引用>看看axios取消
<小时><小时><块引用>
一个简单的例子,你可以现场观看.
HTML:
<button :disabled="!request" @click="cancel">取消</button>
JS
import axios from "axios";导出默认{数据:() =>({要求: [],请求:空}),方法: {发送() {如果 (this.request) this.cancel();this.makeRequest();},取消() {this.request.cancel();this.clearOldRequest("取消");},makeRequest() {const axiosSource = axios.CancelToken.source();this.request = { 取消: axiosSource.cancel, msg: "加载中..." };公理.get(API_URL, { cancelToken: axiosSource.token }).then(() => {this.clearOldRequest("成功");}).catch(this.logResponseErrors);},日志响应错误(错误){如果(axios.isCancel(错误)){console.log("请求已取消");}},clearOldRequest(msg) {this.request.msg = msg;this.requests.push(this.request);this.request = null;}}};
I am using axios
and vue.js
.I have google it,and check the axios docs but still cannot understand how to do it.
解决方案
2020 UPDATE: How to cancel an axios request
generate a cancelToken
and store it
import axios from 'axios'
const request = axios.CancelToken.source();
pass the cancelToken
to the axios request
axios.get('API_URL', { cancelToken: request.token })
Access the request you stored and call the .cancel()
method to cancel it
request.cancel("Optional message");
See it live on a tiny app on codesandbox
Take a look at axios cancellation
A simple example which you can see it live.
HTML:
<button @click="send">Send</button>
<button :disabled="!request" @click="cancel">Cancel</button>
JS
import axios from "axios";
export default {
data: () => ({
requests: [],
request: null
}),
methods: {
send() {
if (this.request) this.cancel();
this.makeRequest();
},
cancel() {
this.request.cancel();
this.clearOldRequest("Cancelled");
},
makeRequest() {
const axiosSource = axios.CancelToken.source();
this.request = { cancel: axiosSource.cancel, msg: "Loading..." };
axios
.get(API_URL, { cancelToken: axiosSource.token })
.then(() => {
this.clearOldRequest("Success");
})
.catch(this.logResponseErrors);
},
logResponseErrors(err) {
if (axios.isCancel(err)) {
console.log("Request cancelled");
}
},
clearOldRequest(msg) {
this.request.msg = msg;
this.requests.push(this.request);
this.request = null;
}
}
};
这篇关于使用 axios 和 vue.js 取消之前的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文