tsx81429 发表于 2024-6-20 19:24:34

vue3 + axios 停止取消接口请求

媒介

近来开发过程中,总是碰到想把正在请求的axios接口取消,这种情况有很多应用场景,举几个例子:

[*]弹窗中接口请求返回图片,用于前端展示,接口还没返回数据,此时关闭弹窗,需要停止接口请求
[*]tab标签页根据后端返回数据,依次渲染,频仍切换标签,需要停止接口请求
[*]for循环中请求接口,碰到跳出循环情况,也需要停止接口请求
[*]跳转路由,离开页面时,可能也需要停止接口请求
下面就是根据以上问题,找到的解决方案
正文

由于axios差别版本取消请求是差别的,目前最新的 axios 的取消请求api,保举使用 AbortController ,旧版本的 CancelToken 在 v0.22.0 后弃用,截止到此片文章发表,npm上的axios版本号已经更新到v1.5.1,但是信任有一些项目标版本还是v0.x.x的,所以下面分别介绍两种取消方式,各人根据自己项目axios版本号,自行查察
https://img-blog.csdnimg.cn/55c6afa4f2c5474aa90a933e21d90fb4.png
v0.22.0 CancelToken


[*]get请求
<el-button type="primary" @click="sendGet()">发送get请求</el-button>
<el-button type="danger" @click="cancel()">取消请求</el-button>

import {ref,onMounted,onUnmounted} from 'vue'
import axios from "axios";

let source:any = null;
const sendGet = ()=>{
        //可以理解为给定每个接口一个标识
source = axios.CancelToken.source();
axios.get('请求url',
      {
      cancelToken: source.token
      }
).then(res => {
    console.log("get请求",res)
}).catch(err => {
    if (axios.isCancel(err)) {
      console.log('请求取消', err);
    } else {
      console.log('其他错误', err)
    }
});
}

const cancel = ()=>{
source && source.cancel('手动调用 source.cancel方法,手动取消请求');
}
https://img-blog.csdnimg.cn/2f9328c6f4db4111996b886935366956.png

[*]post请求
<el-button type="success" @click="sendPost()">发送post请求</el-button>
<el-button type="danger" @click="cancel()">取消请求</el-button>

import {ref,onMounted,onUnmounted} from 'vue'
import axios from "axios";

let source:any = null;
const sendPost = ()=>{
source = axios.CancelToken.source();
axios.post("请求url",
       {},//传参,没有也必须加上{}
       {
         cancelToken: source.token
       })
       .then((res) => {
         console.log("post请求",res)
       }).catch(err => {
   if (axios.isCancel(err)) {
       console.log('请求取消', err);
   } else {
       console.log('其他错误', err)
   }
   })
}

const cancel = ()=>{
source && source.cancel('手动调用 source.cancel方法,手动取消请求');
}
https://img-blog.csdnimg.cn/04a74e0e7d5044cea9b8c6d9fb3e9f91.png
v1.5.1 AbortController

使用fetch() 是一个全局方法,它的请求是基于 Promise 的
method - 请求方法,默认GET
signal - 用于取消 fetch
<el-button type="primary" @click="sendNewGet()">发送get请求</el-button>
<el-button type="danger" @click="cancelController()">取消新版请求</el-button>

import {ref,onMounted,onUnmounted} from 'vue'
import axios from "axios";

let controller:any = null;

const sendNewGet = ()=>{
controller = new AbortController();   // 新建一个AbortController实例
fetch('请求url',
      {
      signal: controller.signal    // signal是AbortController实例的属性
      }
).then(res => {
    console.log("新版get请求",res)
    //处理返回数据
    res.json().then(res1 => {
      console.log(res1)
    })


}).catch(err => {
    console.log(err)
});
}

const cancelController = ()=>{
controller && controller.abort();//调用abort方法
}

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: vue3 + axios 停止取消接口请求