使用axios和vue.js取消上一个请求

ivqmmu1c  于 2022-11-05  发布在  iOS
关注(0)|答案(4)|浏览(251)

我正在使用axiosvue.js。我已经谷歌了它,并检查了axios文档,但仍然不明白如何做。

zysjyyx4

zysjyyx41#

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对象得引用.

为了将信号与请求相关联,我们将信号作为选项传递到请求的options对象中,然后调用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");

See it live on a tiny app on codesandbox
看一看axios取消
一个简单的例子,你可以see it live.

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;
    }
  }
};
q3aa0525

q3aa05252#

在这个例子中,当一个新的请求开始时,当前的请求被取消。如果在旧的请求被取消之前有一个新的请求被触发,服务器会在5秒后应答。cancelSource指定了一个可以用来取消请求的取消令牌。有关更多信息,请查看axios文档。
第一个

qco9c6ql

qco9c6ql3#

下面是我在一家Pinia商店里的做法:

import { defineStore } from 'pinia';

export const useSomeStore = defineStore('some', {
    state: () => ({
        someList: [],
        abortController: null,
    }),

    actions: {
        async getSomeList() {
            try {
                if (this.abortController) {
                    this.abortController.abort();
                }

                this.abortController = new AbortController();
                const signal = this.abortController.signal;

                axois.get('admin/providers/list', { signal })
                    .then((res) => {
                        this.someList = res.data.data;
                        this.abortController = null;
                    }).catch((err) => {
                        this.isFetching = false;
                    });
            } catch (error) {
                console.log('error', error);
                throw error;
            }
        },
    },
});

重要的是:

// step 1: if abortController is active, it means a request 
            // is in progress and we need to cancel it before proceeding
            if (this.abortController) {
                this.abortController.abort();
            }

            // step 2: abortController wasnt active, so activate one
            // and grab its signal
            this.abortController = new AbortController();
            const signal = this.abortController.signal;

            // step 3: make request and pass in signal
            await axios.get('admin/providers/list', { signal });

            // step 4: unset the abortController after request is done
            this.signalController = null;
xuo3flqw

xuo3flqw4#

首先定义一些变量

data: function () {
    return {
        request_source : ''
    }
},

然后在方法内部

source = CancelToken.source();
if(this.request_source != '')
    this.request_source.cancel('Operation canceled by the user.');

this.request_source = source;

axios
   .get(
       URL,
          {
              params:{key1: value1},
              cancelToken: this.request_source.token
          }
    )

相关问题