1. 程式人生 > 其它 >axios 如何取消請求

axios 如何取消請求

Axios 中提供了一個CanCelToken的函式,這是個建構函式,該函式的作用就是用來取消介面請求的,官方地址:

https://javasoho.com/axios/index.html#%E5%8F%96%E6%B6%88

程式碼如下:

<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就行了,newthis.axios.CancelToken(functionexecutor(c){ that.source=c; }) ,儲存取消函式

取消的時候直接呼叫即可