使用Axios取消Vue.js中的多个API调用

Lov*_*ock 5 ajax vue.js axios vuejs2

我正在使用一个带有多个"模块"的仪表板,每个模块都有自己的API调用.大多数端点很快,但有一些可能需要几秒钟.

我有一个日期范围的过滤选项,每次更改时我都会运行数据的API调用.

问题是,如果用户在其他人加载之前不断快速更改日期范围,我不希望用户能够堆叠API调用.

我使用单个文件vue组件,并为每个API调用提供一个方法,然后使用一个方法对这些组进行分组和调用.

watch: {
    dateFilter: function() {
        this.initStatModules();
    }
},
methods: {
    getCustomers: function() {
        var $this = this;
        return axios.get(`/api/v1/reports/${$this.team.id}/stats-dashboard/customers?date=${$this.dateFilter}`).then(function(response) {
            $this.customers = response.data;
        });
    },
    getBookings: function() {
        var $this = this;
        return axios.get(`/api/v1/reports/${$this.team.id}/stats-dashboard/bookings`).then(function(response) {
            $this.bookings = response.data;
        });
    },
    getTotalRevenue: function() {
        var $this = this;
        return axios.get(`/api/v1/reports/${$this.team.id}/services-revenue?date=${$this.dateFilter}`).then(function(response) {
            $this.totalRevenue = response.data.data.totalRevenue;
        });

    },
    initStatModules: function() {
        this.getCustomers();
        this.getBookings();
        this.getTotalRevenue();
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望能够做的是取消watch或initStatModules方法中的所有挂起的API请求.

看看axios docs:https://github.com/axios/axios#cancellation它是受支持的,但是我无法理解如何按照自己的意愿实现它.

谢谢!

cas*_*ral 0

我建议避免调用而不是取消,Axios 说它是在草案上实现的,在这种情况下,看起来避免调用就足够了。

我的意思是:

不要让用户过滤是否发生过滤器调用。您还需要使用 async/await 或 Promises 来更好地控制。

例如,一个数据属性,例如:

isFiltering: false
Run Code Online (Sandbox Code Playgroud)

像您一样使用承诺(此处省略您的代码,但其他方法的想法相同):

methods: {
  getCustomers: async function () {
      var $this = this;
      this.isFiltering = true;
      return axios.get(`/api/v1/reports/${$this.team.id}/stats-dashboard/customers?date=${$this.dateFilter}`).then(function(response) {
          $this.customers = response.data;
          $this.isFiltering = false;
      });
  }
}
Run Code Online (Sandbox Code Playgroud)

在您的 HTML 中,使用isFiltering来禁用(添加 CSS 或您希望的任何方式)输入。这将阻止用户更改过滤并且看起来过滤正在执行。请记住添加部分以在出现问题时.catch将其设置为 false。isFiltering使用.finallyif is available 会更好

if isFiltering then disable

另一种方法是使用Lodash 的Throttle或任何其他解决方案,或者这里建议的实现:Simplethrottle in js

该限制选项可以更好地避免连续调用,例如当用户输入内容时。