Axios 中提供了一個CanCelToken的函數,這是個構造函數,該函數的作用就是用來取消接口請求的,官方地址:
代碼如下:
<template>
<div>
<el-button @click="startClick">
開始請求
</el-button>
<br />
<hr />
<el-button @click="endClick">
取消請求
</el-button>
</div>
</template>
<script>
export default {
data() {
return {
source: null, //存放取消的請求方法
};
},
methods: {
startClick() {
this.getInfo();
},
endClick() {
this.cancelQuest();
},
cancelQuest() {
if (typeof this.source === "function") {
this.source("終止請求"); //取消請求
}
},
getInfo() {
const _this = this;
this.cancelQuest(); //在請求發出前取消上一次未完成的請求;
//發送請求
this.axios
.get(`/test/data/check/updateExamRoom`, {
cancelToken: new this.axios.CancelToken(function executor(c) {
_this.source = c;
}),
})
.then((res) => {
//handle result
})
.catch((err) => {
console.log(err);
if (this.axios.isCancel(err)) {
console.log("Rquest canceled", err.message); //請求如果被取消,這里是返回取消的message
} else {
//handle error
console.log(err);
}
});
},
},
};
</script>
<style lang="scss"></style>
分析:主要是在發送axios請求時,再添加一個cancelToken的參數,它的值是一個構造函數;注意這個構造函數里面自帶取消請求的函數,再我們需要取消請求的時候,調用這個函數即可(在請求的時候需要把這個函數給保存下來)
題外話:每個人的項目接口基本上都是封裝好的,可根據不同的封裝進行修改,把這個cancelToken參數添加進去就可以了,比如我的項目中接口在單獨的js文件中

調用接口的時候傳入這個cancelToken就行了,new this.axios.CancelToken(function executor(c) { that.source = c; }) ,保存取消函數

取消的時候直接調用即可

