我正在使用 Vue Resource从 REST API 检索图像集合。请求在我的 Vue 组件的 created
Hook 中发送。
问题是,我试图在 mounted
Hook 中访问检索到的数据,但数据未加载。
我在控制台中收到此错误:
[Vue warn]: Error in mounted hook: "TypeError: Cannot read property 'forEach' of undefined"
这是我的组件:
<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>
如果我将 setTimeout
包裹在 mounted
的内容周围,一切正常。
所以,我不明白如何在执行 mounted
Hook 之前等待我的数据加载。这不就是 Vue 生命周期钩子(Hook)的作用吗?
最佳答案
由于 this.imgs.query()
调用是异步的,您的 mounted
Hook 在 then
处理程序设置 this.imgs
(我假设它与 v-for
绑定(bind)到模板中具有属性 ref="image"
的元素).因此,即使组件已挂载到 DOM,$refs
仍未设置。
我会创建一个方法来“用 imgs 做一些事情”,然后在 $nextTick
callback 中调用该方法在异步调用的 then
处理程序中。传递给 $nextTick
的回调将“在下一个 DOM 更新周期后执行”,这意味着 $refs
将在此时设置。
<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;
this.$nextTick(() => this.doStuffWithImgs());
}, (response) => {
console.log('erreur', response);
});
},
methods: {
doStuffWithImgs() {
// get the ref="image" in my dom template
let imgs = this.$refs.image;
imgs.forEach((img) => {
// I do some stuff with imgs
});
}
}
}
</script>
关于vue.js - mounted 方法在加载数据之前被触发 - VueJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47717415/