ajax – 使用Axios取消Vue.js中的多个API调用
发布时间:2020-12-16 02:56:23 所属栏目:百科 来源:网络整理
导读:我正在使用一个带有多个“模块”的仪表板,每个模块都有自己的API调用.大多数端点很快,但有一些可能需要几秒钟. 我有一个日期范围的过滤选项,每次更改时我都会运行数据的API调用. 问题是,如果用户在其他人加载之前不断快速更改日期范围,我不希望用户能够堆叠A
|
我正在使用一个带有多个“模块”的仪表板,每个模块都有自己的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>
试试这个. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
