<script>
import axios from 'axios';
let keywordListArray = [];
export default {
data() {
return {
items: [],
targetKeyword: {}
}
},
created() {
console.log("LifeCycleHook: created");
this.removeItems();
console.log("checkpoint 1");
this.callSearchApi();
console.log("checkpoint 2");
console.log("keywordListArray length:", keywordListArray.length);
console.log("checkpoint 3");
this.items = keywordListArray;
console.log("this.items info:", this.items);
console.log("checkpoint 4");
this.targetKeyword = keywordListArray[0];
console.log("this.targetKeyword info:", this.targetKeyword);
console.log("checkpoint 5");
},
beforeUpdate() {
console.log("LifeCycleHook: beforeUpdate");
console.log("keywordListArray length:", keywordListArray.length);
this.targetKeyword = keywordListArray[0]
console.log("this.targetKeyword info:", this.targetKeyword);
console.log("checkpoint 6");
},
methods: {
removeItems: function () {
console.log("checkpoint 7");
keywordListArray = [];
console.log("keywordListArray init complete!");
},
callSearchApi: function () {
console.log("checkpoint 8");
axios.get('http://localhost:5000/api/v1/searchs', {
params: {
hintKeywords: this.$route.params.keyword
}
})
.then((result) => {
{
let keywordList = result.data.keywordList;
for (const i in keywordList) {
keywordListArray.push(keywordList[i]);
}
console.log("keywordListArray push complete!");
}
})
.catch(function (error) {
console.log(error);
alert('Network Error');
return false;
})
.then(function () {
console.log('finish ApiConnection!');
});
}
},
name: "SearchResult"
}
</script>
이게 문제의 코드와 실행 순서 결과인데요
Vue의 라이프사이클을 봤을 때
created 단계에서 removeItems(배열 초기화 메서드) 이후에 callSearchApi 메서드를 호출합니다.
그런데 callSearchApi는 axios를 통한 비동기 요청이므로 callSearchApi 메서드 이후 코드인
checkpoint2부터 checkpoint5까지 먼저 코드 진행이 되는 것으로 알고 있습니다.
때문에 크롬 개발자 도구에서도 보면 당연히 아직 axios 요청 전이므로
코드에서 checkpoint2 이후 코드인 아래 결과가 0이 찍히고(Q1)
console.log("keywordListArray length:", keywordListArray.length);
checkpoint4 이후 코드인 아래 결과가 undefined(Q2)가 나오는 것이 이해가 됩니다.
console.log("checkpoint 4");
this.targetKeyword = keywordListArray[0];
console.log("this.targetKeyword info:", this.targetKeyword);
그렇다면 checkpoint3 이후 코드인 아래의 경우 keywordListArray는 length가 0인 빈배열인데
왜 개발자도구에선 (Q3) 데이터가 출력이 되는 것인가요??
console.log("checkpoint 3");
this.items = keywordListArray;
console.log("this.items info:", this.items);
콘솔창에 따르면
checkpoint5까지 먼저 코드가 실행되고 나서 axios 비동기 요청이 찍히는데요
해당 비동기 요청으로 받은 데이터를 배열에 push 하는 과정을 통해
Vue 인스턴스가 관찰하고 있던 데이터 items에 변화가 생긴것은 axios 요청에서
배열에 push하기 전인데요...
라이프사이클에 따른다면 checkpoint 3, 사진에서 Q3에 마찬가지로 undefined가 나온 후
beforeupdate 단계에서 Q4와 마찬가지로 변화된 데이터가 감지되어야 하는 것 아닌가요??
해결이 안되서 질문드립니다!