如何实现按钮自动每分钟调用API并计算前5条数据平均值
解决方案
针对你的需求——点击Submit按钮后自动每分钟调用一次API,累计收集60条数据,同时计算列表前5条的平均值,下面是调整后的完整实现:
核心修改要点
- 补充
currency初始定义与定时器ID存储变量,避免未定义报错和内存泄漏 - 改造
getData方法,每次调用仅添加单条数据(原代码的for循环会一次性插入59条重复数据,不符合需求) - 新增定时任务逻辑,点击Submit后启动每分钟调用,数据满60条自动停止
- 添加平均值计算方法,处理数据不足的边界情况
- 组件销毁时清理定时器,避免无效任务持续运行
完整代码
<template> <div> <form> <label>输入货币代码: <input type="text" v-model="currency" placeholder="例如USD"></label> <input id="clickMe" type="button" value="Submit" @click="startAutoFetch" /> </form> <div v-if="amountList.length >= 5"> <p>前5条数据平均值: {{ calculateAverage() }}</p> </div> <ul> <li v-for="(item, index) in amountList" :key="index"> 第{{ index + 1 }}条: {{ item }} </li> </ul> </div> </template> <script> // eslint-disable-next-line no-unused-vars import axios from 'axios' export default { data() { return { apiEndPoint: 'https://api.coinbase.com/v2/prices/spot?currency=', apiData: [], amountList: [], currency: '', fetchTimer: null } }, beforeUnmount() { if (this.fetchTimer) { clearInterval(this.fetchTimer) } }, methods: { getShortList(shortListSize) { return this.amountList.slice(0, shortListSize) }, async getData(currency) { if (!currency) return try { const response = await axios.get(`${this.apiEndPoint}${currency}`) const amount = response.data.data.amount this.amountList.push(amount) console.log(`新增数据: ${amount}`) if (this.amountList.length >= 60) { clearInterval(this.fetchTimer) this.fetchTimer = null console.log('已收集60条数据,停止自动调用') } } catch (error) { console.error('API调用失败:', error) } }, startAutoFetch() { this.getData(this.currency) if (this.fetchTimer) { clearInterval(this.fetchTimer) } this.fetchTimer = setInterval(() => { this.getData(this.currency) }, 60 * 1000) }, calculateAverage() { const shortList = this.getShortList(5) if (shortList.length < 5) return '数据不足5条' const sum = shortList.reduce((total, num) => total + parseFloat(num), 0) return (sum / 5).toFixed(2) } } } </script>
关键说明
- 定时任务逻辑:点击Submit后立即获取第一条数据,随后启动每分钟的定时调用,数据满60条时自动终止任务,避免无效请求。
- 平均值计算:通过
getShortList获取前5条数据,转数字求和后取平均,用toFixed(2)格式化结果保证可读性。 - 错误与边界处理:捕获API调用异常,避免程序崩溃;数据不足5条时给出提示,提升用户体验。
- 内存防护:组件销毁时清理定时器,防止组件卸载后定时任务仍在后台运行。
内容的提问来源于stack exchange,提问作者xristis paras
相关产品推荐
相关产品推荐

