我正在使用一个带有多个“模块”的仪表板,每个模块都有自己的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 docs:https://github.com/axios/axios#cancellation它是受支持的,但是我无法理解如何按照我的意愿实现它.
谢谢!
解决方法
<template> <input type="date" :disabled="isdisabled" v-model="datefilter"> </template> <script> export default { data () { return { datefilter: null,modulesLoaded: 0,isdisabled: false } },watch: { datefilter () { this.initStatModules() } },methods: { getCustomers () { axios.get(`/api/v1/reports/${$this.team.id}/stats-dashboard/customers?date=${$this.datefilter}`) .then(response => { this.customers = response.data this.onModuleLoaded() }) },getBookings () { axios.get(`/api/v1/reports/${$this.team.id}/stats-dashboard/bookings`) .then(response => { this.bookings = response.data this.onModuleLoaded() }) },getTotalRevenue () { axios.get(`/api/v1/reports/${$this.team.id}/services-revenue?date=${$this.datefilter}`) .then(response => { this.totalRevenue = response.data.data.totalRevenue this.onModuleLoaded() }) },initStatModules () { this.isdisabled = true this.modulesLoaded = 0 this.getCustomers() this.getBookings() this.getTotalRevenue() },onModuleLoaded () { this.modulesLoaded++ if (this.modulesLoaded === 3) { this.isdisabled = false } } } } </script>
试试这个.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。