gpt4 book ai didi

ajax - 使用 Axios 在 Vue.js 中取消多个 API 调用

转载 作者:搜寻专家 更新时间:2023-10-30 22:13:44 24 4
gpt4 key购买 nike

我正在开发一个包含多个“模块”的仪表板,每个模块都有自己的 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它受支持,但我不知道如何按照我的意愿实现它。

谢谢!

最佳答案

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

我的意思是:

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

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

isFiltering: false

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

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 会更好

如果 isFiltering 则禁用

另一种方法是使用 Throttle来自 Lodash 或任何其他解决方案,或在 S.O. 上建议的此实现:Simple throttle in js

限制选项只是为了更好地避免连续调用,例如当用户正在输入时。

关于ajax - 使用 Axios 在 Vue.js 中取消多个 API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46492000/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com