vue3 + axios 中断取消接口请求

前言

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

  1. 弹窗中接口请求返回图片,用于前端展示,接口还没返回数据,此时关闭弹窗,需要中断接口请求
  2. tab标签页根据后端返回数据,依次渲染,频繁切换标签,需要中断接口请求
  3. for循环中请求接口,遇到跳出循环情况,也需要中断接口请求
  4. 跳转路由,离开页面时,可能也需要中断接口请求

下面就是根据以上问题,找到的解决方案

正文

因为axios不同版本取消请求是不同的,目前最新的 axios 的取消请求api,推荐使用 AbortController ,旧版本的 CancelToken 在 v0.22.0 后弃用,截止到此片文章发表,npm上的axios版本号已经更新到v1.5.1,但是相信有一些项目的版本还是v0.x.x的,所以下面分别介绍两种取消方式,大家根据自己项目axios版本号,自行查看

在这里插入图片描述

v0.22.0 CancelToken

  1. 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方法,手动取消请求');
}

在这里插入图片描述

  1. 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方法,手动取消请求');
}

在这里插入图片描述

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方法
}

猜你喜欢

转载自blog.csdn.net/qq_37656005/article/details/133938807