gpt4 book ai didi

vue.js - 如何每 x 秒调用一个方法?

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

我需要每秒调用方法 getBitcoins()。

Tried: I tried just taking it out the methods and putting it under the line import Pickaxe from '../assets/pickaxe.png' and then using setInterval to call it every second, but then I can't access the data variable btcPrice inside getBitcoins().

所以我需要一种每秒从方法函数中调用 getBitcoins() 的方法,就像在下面的代码中一样。

<template>
<div id="wrapper">
<div class="top"></div>
<!-- Center -->
<div class="center">
<img :src="Pickaxe" class="Pickaxe">
<span class="my-btc">{{ mybtc.toFixed(8) }}</span>
<span id="btc">1 BTC = {{ btcPrice }}</span>
<button class="Mine">Mine</button>
<span class="hashes">{{btcMin}} btc/min</span>
<button class="Upgrade">UPGRADE</button>
<span class="upgradePrice">{{ upgradePrice }}btc</span>
</div>
</div>
</template>

<script>
import bitcoin from '../assets/bitcoin.svg'
import Pickaxe from '../assets/pickaxe.png'

export default {
name: 'landing-page',
data() {
return {
bitcoin,
Pickaxe,

mybtc: 1,
btcPrice: null,
btcMin: 0,

upgradePrice: 0

}
},
methods: {
getBitcoins() {
var currentPrice = new XMLHttpRequest();
currentPrice.open('GET', 'https://api.gdax.com/products/BTC-USD/book', true);
currentPrice.onreadystatechange = function(){
if(currentPrice.readyState == 4){
let ticker = JSON.parse(currentPrice.responseText);
let price = ticker.bids[0][0];
document.getElementById('btc').innerHTML = "1 BTC = " + price + "$";
};
};
currentPrice.send();
}
}
}
</script>

最佳答案

我认为这应该可以满足您的需求。

created() {
this.interval = setInterval(() => this.getBitcoins(), 1000);
},

不必在创建的事件上注册它,您可以在其他方法上注册它,甚至在观察者上注册。如果你那样做,你将不得不以某种方式检查它是否没有被注册,因为它可能会导致多个循环同时运行。

关于vue.js - 如何每 x 秒调用一个方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52025790/

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