axios 如何取消请求

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;  })  ,保存取消函数

取消的时候直接调用即可

 

原文地址:https://www.cnblogs.com/m1754171640/p/15117241.html