【发布时间】:2018-05-22 21:07:04
【问题描述】:
我正在使用Vue Resource 从 REST API 检索图像集合。请求在我的 Vue 组件的 created 钩子中发送。
问题是,我正在尝试访问 mounted 挂钩中检索到的数据,但未加载数据。
我在控制台中收到此错误:
[Vue 警告]:挂载钩子错误:“TypeError:无法读取未定义的属性 'forEach'”
这是我的组件:
<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 挂钩之前等待我的数据加载。这不就是 Vue 生命周期钩子的作用吗?
【问题讨论】:
-
为什么不直接使用 created()?
-
因为
created中没有任何反应。在mounted钩子之前你不能操作 DOM。 check this documentation。如果我只使用一个生命周期钩子,这将是完全相同的问题。我想使用的内容没有加载。
标签: vue.js lifecycle vue-resource