我在 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);
}
}
}
最佳答案
计算属性只有在它的某些依赖项发生变化时才会重新评估,这意味着如果我们可以这样说,它们就有某种“缓存”。 See: Computed caching vs Methods
另一件事是,当mounted() 时,您正在运行Axios get 调用,这意味着您的调用仅在组件安装后才运行,根本不会刷新。 See: Lifecycle Diagram
我对您的问题的解决方案是这样的:
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();
}
}
我认为这是一个合理的解决方案,请随意测试一下。
关于vue.js - 如何在 vuejs 中自动刷新 axios 的计算属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54601694/