Vue Resource을 사용하여 REST API에서 이미지 컬렉션을 검색합니다. 요청은 내 Vue 구성 요소의 created
후크로 전송됩니다.데이터로드 전에 마운트 된 메소드가 실행됩니다. - VueJS
문제는 검색된 데이터에 mounted
후크에 액세스하려고하는데 데이터가로드되지 않았기 때문입니다.
내가 콘솔에서이 오류를 얻을 :
[Vue warn]: Error in mounted hook: "TypeError: Cannot read property 'forEach' of undefined"
여기 내 구성 요소입니다 : 내가 mounted
의 내용을 주위에 setTimeout
을 포장하는 경우
<script>
export default {
data() {
return { imgs : '' };
},
created() {
// the full url is declare in my main.js
this.imgs = this.$resource('acf/v3/pages/4');
this.imgs.query().then((response) => {
console.log('success', response);
this.imgs = response.data.acf.gallery;
}, (response) => {
console.log('erreur', response);
});
},
mounted() {
// get the ref="image" in my dom template
let imgs = this.$refs.image;
imgs.forEach((img) => {
// I do some stuff with imgs
});
}
}
</script>
, 모든 것이 잘 작동합니다.
따라서 mounted
후크가 실행되기 전에 데이터가로드 될 때까지 기다리는 방법을 모르겠다. Vue 라이프 사이클 후크의 역할이 아닌가? this.imgs.query()
호출이 비동기이기 때문에 then
핸들러가 this.imgs
(나는 속성 ref="image"
와 템플릿의 요소에 v-for
와 결합되고 있으리라 믿고있어하는)를 설정하기 전에
왜 created()를 사용하지 않으시겠습니까? – samayo
'created '에 반응이 없으므로. 'mounted' 훅 전에 DOM을 조작 할 수 없습니다. [이 문서를 확인하십시오] (https://alligator.io/vuejs/component-lifecycle/). 그리고 하나의 lifeCycle 후크 만 사용하면 똑같은 문제가 발생합니다. 내 콘텐츠를 사용하고 싶을 때 콘텐츠가로드되지 않습니다. – BrownBe