반응형
vuejs의 Axios에서 계산된 속성을 자동으로 새로 고치는 방법
vuejs에 있는 악시들을 사용하여 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);
}
}
}
계산된 속성은 종속성 중 일부가 변경된 경우에만 재평가됩니다. 즉, 이렇게 표현하면 "캐시"가 있다는 것을 의미합니다.참조: 계산 캐싱과 메서드
또 하나는 Axios get call을 mounted()로 실행하고 있다는 것입니다.즉, 콜은 컴포넌트가 마운트된 후에만 실행되며 새로고침은 전혀 이루어지지 않습니다.참조: 라이프 사이클 다이어그램
귀사의 문제에 대한 저의 해결책은 다음과 같습니다.
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();
}
}
저는 이것이 그럴듯한 해결책이라고 생각하는데, 부담없이 시험해 보세요.
언급URL : https://stackoverflow.com/questions/54601694/how-to-auto-refresh-a-computed-property-at-axios-in-vuejs
반응형
'programing' 카테고리의 다른 글
잭슨 VS지손 (0) | 2022.09.03 |
---|---|
구조체 배열 끝에 빈 중괄호 '{ }'가 필요한 이유는 무엇입니까? (0) | 2022.09.01 |
어떻게 목록의 자바에 있는 모든 요소들을 인쇄할? (0) | 2022.09.01 |
기본적으로 5가 아닌 웹 팩 4를 사용하는 Vue CLI (0) | 2022.09.01 |
vuex / nuxtClientInit용 후크가 생성되었습니까? (0) | 2022.09.01 |