trm*_*rmt 3 setinterval vue.js axios vuejs2
我在 vuejs 中使用 axios 调用 restapi 数据,我希望这些数据每秒自动刷新以查看数字的任何变化。我可以看到数据,它正在工作,但刷新不起作用
我已经将 setinterval 函数放在方法区域中,但它不会刷新任何数据。
import axios from 'axios';
export default {
data () {
return {
btctrk: null,
bnnc: null,
}
},
computed: {
result1: function(){
return this.btctrk[0].ask / this.btctrk[4].bid;
},
result2: function(){
return this.btctrk[0].bid / this.btctrk[4].ask;
},
result3: function(){
return (1-(this.bnnc[11].bidPrice / this.result1))*100;
},
result4: function(){
return (1-(this.result2 / this.bnnc[11].askPrice))*100;
},
},
mounted () {
axios
.get('https://www.api1.com/api/ticker')
.then(response => (this.btctrk = response.data))
.catch(error => console.log(error))
axios
.get('https://api.api2.com/api/v3/ticker/bookTicker')
.then(response => (this.bnnc = response.data))
.catch(error => console.log(error))
},
methods: {
startInterval: function () {
setInterval(() => {
this.result1;
this.result2;
this.result3;
this.result4;
}, 1000);
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 7
计算属性仅在其某些依赖项发生更改时才重新评估,这意味着如果我们可以这样放置它们,则它们具有某种“缓存”。请参阅:计算缓存与方法
另一件事是您在mounted() 时正在运行您的Axios get 调用,这意味着您的调用仅在组件安装后运行并且根本不刷新。请参阅:生命周期图
我对您的问题的解决方案将是这样的:
export default {
data () {
return {
btctrk: null,
bnnc: null,
}
},
computed: {
result1: function(){
return this.btctrk[0].ask / this.btctrk[4].bid;
},
result2: function(){
return this.btctrk[0].bid / this.btctrk[4].ask;
},
result3: function(){
return (1-(this.bnnc[11].bidPrice / this.result1))*100;
},
result4: function(){
return (1-(this.result2 / this.bnnc[11].askPrice))*100;
},
},
methods: {
btcTrkAPICall: function () {
axios
.get('https://www.api1.com/api/ticker')
.then(response => (this.btctrk = response.data))
.catch(error => console.log(error))
},
bnncAPICall: function () {
axios
.get('https://api.api2.com/api/v3/ticker/bookTicker')
.then(response => (this.bnnc = response.data))
.catch(error => console.log(error))
},
intervalFetchData: function () {
setInterval(() => {
this.btcTrkAPICall();
this.bnncAPICall();
}, 1000);
}
},
mounted () {
// Run the functions once when mounted
this.btcTrkAPICall();
this.bnncAPICall();
// Run the intervalFetchData function once to set the interval time for later refresh
this.intervalFetchData();
}
}
Run Code Online (Sandbox Code Playgroud)
我认为这是一个合理的解决方案,请随时测试。
| 归档时间: |
|
| 查看次数: |
6149 次 |
| 最近记录: |