试图每分钟一次调用API,而不是在用户重新加载时
这就是我现在拥有的。 在我的安装()上,我有fetchcoins(),但是每当用户刷新用户时,API被称为
我试图制作它,因此API称为数据,然后每分钟存储数据,然后每分钟获取数据
methods: {
async fetchCoins() {
const response = await fetch("https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=false&price_change_percentage=1h");
const data = await response.json();
this.coins = this.coins.concat(data);
},
setData() {
localStorage.setItem('coin-info', JSON.stringify(this.coins))
},
getData() {
let get = localStorage.getItem('coin-info', []);
this.coins = JSON.parse(get);
console.log(this.coins);
setInterval(() => {
this.fetchCoins()
}, 60000);
},
}
This is what I have right now.
On my mounted() I have fetchCoins() but that makes it so whenever a user refreshes, the API is called
I'm trying to make it so the API is calledthe data is stored in localstorage, then getting the data every minute
methods: {
async fetchCoins() {
const response = await fetch("https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=false&price_change_percentage=1h");
const data = await response.json();
this.coins = this.coins.concat(data);
},
setData() {
localStorage.setItem('coin-info', JSON.stringify(this.coins))
},
getData() {
let get = localStorage.getItem('coin-info', []);
this.coins = JSON.parse(get);
console.log(this.coins);
setInterval(() => {
this.fetchCoins()
}, 60000);
},
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要在LocalStorage中跟踪最后一次提取的日期。这是一个示例实现:
您需要将呼叫更改为
this.fetchcoins()
在已安装的
函数中。但是请记住,有关此片段有几个警告(出于问题的范围):
settimeout
和setInterval
并不是完全准确的时间函数。它们可能会被一些毫秒拖延。如果您担心这种无关,请查看一些其他问题,这些问题提出了解决方案,例如这个。coin-info-last-fetch
。settimeout
返回的超时ID存储在组件的数据中,以最终清除它。You need to keep track in localStorage about the date when the last fetch happened. Here is an example implementation:
You need to change the call to
this.fetchCoins()
in themounted
function for this one.But keep in mind that there are a couple of caveats about this snippet (out of the scope of the question):
setTimeout
andsetInterval
are not not totally accurate time functions. They could be delayed by some milliseconds. If you are concerned about this innacuracy, have a look at some other questions that propose solutions such as this one.coin-info-last-fetch
.setTimeout
in the data of the component to be able to eventually clear it.