axios取消上一个请求,亲测有效

 

 

链接,里面有效果,亲测有效果

https://codesandbox.io/s/simple-example-of-cancelling-axios-request-kyrnc?file=/src/App.vue:1074-1096

这个可能需要外网才能打开,要不然有点卡,本人亲测有效,axios版本是0.22.0.。他们版本是"axios": "0.19.2",

代码放出来

<template>
  <div id="app">
    Open browser devtools in network tab to see requests
    <hr>
    <button @click="send">Send</button>
    <button :disabled="!request" @click="cancel">Cancel</button>
    <hr>
    <DisplayRequests :requests="requests" :request="request"/>
  </div>
</template>

<script>
import axios from "axios";
import DisplayRequests from "./components/DisplayRequests";

const API_URL = "https://reqres.in/api/users?delay=2";

export default {
  name: "App",

  components: { DisplayRequests },

  data: () => ({
    requests: [],
    request: null
  }),

  methods: {
    send() {
      if (this.request) this.cancel();
      this.makeRequest();
    },

    cancel() {
      this.request.cancel();
      this.clearOldRequest("Cancelled");
    },

    makeRequest() {
      const axiosSource = axios.CancelToken.source();
      this.request = { cancel: axiosSource.cancel, msg: "Loading..." };
      axios
        .get(API_URL, { cancelToken: axiosSource.token })
        .then(() => {
          this.clearOldRequest("Success");
        })
        .catch(this.logResponseErrors);
    },

    logResponseErrors(err) {
      if (axios.isCancel(err)) {
        console.log("Request cancelled");
      }
    },

    clearOldRequest(msg) {
      this.request.msg = msg;
      this.requests.push(this.request);
      this.request = null;
    }
  }
};
</script>

<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

 

 

只要关心sendd点击事件就行了

 

 

 

 

 

 

 

 

2.还可以参考

https://stackoverflow.com/questions/50516438/cancel-previous-request-using-axios-with-vue-js

https://github.com/axios/axios#cancellation

 

posted @ 2022-10-10 01:07  漫漫长路</>  阅读(172)  评论(0编辑  收藏  举报