2017-09-29 60 views
2

我正在使用多个“模块”,每个模块都有自己的API调用。大多数终点都很快,但有一对夫妇可能需要几秒钟的时间。用Axios取消Vue.js中的多个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(); 
    } 
} 

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

看着axios文档:https://github.com/axios/axios#cancellation它被支持,但我无法让我的脑袋围绕如何实现它,因为我希望。

谢谢!

回答

0

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

我的意思是说:

如果是有一个过滤器调用发生,不要让用户过滤器。您需要使用async/await或Promises来更好地控制它。

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

isFiltering: false 

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

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

在你HTML使用isFiltering禁用(添加CSS或任何你想要的)输入。这将阻止用户更改过滤,并且看起来像过滤正在执行。如果出现问题,请记得添加.catch部分以将isFiltering设置为false。使用.finally如果是可用的就更好了

if isFiltering then disable

另一种方法是使用Throttle从Lodash或任何其他解决方案,或者该实现这里提出的SO:Simple throttle in js

为节气门选项就是更好地避免连续的呼叫,例如当用户输入一个输入时。

+0

谢谢,这是我的备份选项,但你帮助解释它。所有过滤都是通过下拉菜单完成的,所以我现在将禁用它们。希望API调用足够快,不需要太多,但我知道Chrome已经停滞了几次。 – Lovelock

+0

是的,我知道它是怎么回事。我同意,如果用户错误地选择了错误的输入(下拉选择),如果花了那么长时间,等待会很烦人。但是imo防止​​它更可测试和保证行为。因为我不想太依赖取消行为。但最终这是你的呼叫。祝你好运=) – cassioscabral