在 vue.js 中使用 axios 取消之前的请求

新手上路,请多包涵

我正在使用 axiosvue.js 。我用谷歌搜索了它,并查看了 axios 文档,但仍然无法理解如何去做。

原文由 Ready Dev 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 738
2 个回答

2022 更新

要取消请求,请使用 AbortController

 const controller = new AbortController();
const signal = controller.signal

axios.get('/foo/bar', { signal })
.then(function(response) {
   //...
});

// cancel the request
controller.abort()

说明: 我们首先使用 AbortController 创建一个控制器,并通过访问 AbortController.signal 属性获取对其关联的 AbortSignal 对象的引用。

然后为了将信号与请求相关联,我们将该信号作为选项传递到请求的选项对象中。然后取消/中止我们调用 controller.abort() 的请求。

令人惊奇的是,我们可以用与 fetch API 完全相同的方式使用它:

 const controller = new AbortController();
const signal = controller.signal

fetch('/foo/bar', { signal })
.then(function(response) {
   //...
});

// cancel the request
controller.abort()



自 v0.22.0 以来,取消令牌已被弃用,不应在新项目中使用。

2020 年更新:如何取消 axios 请求

生成一个 cancelToken 并存储它

import axios from 'axios'
const request = axios.CancelToken.source();

cancelToken 传递给 axios 请求

axios.get('API_URL', { cancelToken: request.token })

访问你存储的请求,调用 .cancel() 方法取消它

request.cancel("Optional message");

在 codesandbox 上的一个小应用程序上实时查看它



看一下 axios取消



一个简单的例子,你可以 在现场看到它。

HTML:

 <button @click="send">Send</button>
<button :disabled="!request" @click="cancel">Cancel</button>

JS

 import axios from "axios";

export default {
  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;
    }
  }
};

原文由 Roland 发布,翻译遵循 CC BY-SA 4.0 许可协议

在此示例中,当前请求在新请求启动时取消。如果在取消旧请求之前触发了新请求,则服务器会在 5 秒后做出响应。 cancelSource 指定可用于取消请求的取消标记。有关更多信息,请查看 axios 文档

 new Vue({
  el: "#app",
  data: {
      searchItems: null,
      searchText: "some value",
      cancelSource: null,
      infoText: null
  },
  methods: {
    search() {
      if (this.searchText.length < 3)
      {
        return;
      }

      this.searchItems = null;
      this.infoText = 'please wait 5 seconds to load data';

      this.cancelSearch();
      this.cancelSource = axios.CancelToken.source();

      axios.get('https://httpbin.org/delay/5?search=' + this.searchText, {
        cancelToken: this.cancelSource.token }).then((response) => {
          if (response) {
            this.searchItems = response.data;
            this.infoText = null;
            this.cancelSource = null;
          }
        });
    },
    cancelSearch () {
      if (this.cancelSource) {
        this.cancelSource.cancel('Start new search, stop active search');
        console.log('cancel request done');
      }
    }
  }
})
 <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <input v-model="searchText" type="text" />
  <button @click="search">Search</button>{{infoText}}
  <pre>
  {{searchItems}}
  </pre>
</div>

原文由 live2 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题