I'm using Vue Resource to retrieve an images collection from a REST API. The request is sent in the created
hook of my Vue component.
The problem is, I'm trying to access the retrieved data in the mounted
hook, but the data isn't loaded.
I get this error in the console:
[Vue warn]: Error in mounted hook: "TypeError: Cannot read property 'forEach' of undefined"
Here is my component:
<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>
If I wrap a setTimeout
around the content of mounted
, everything works fine.
So, I don't understand how I can wait for my data to load before the mounted
hook is executed. Isn't this the role of the Vue lifecycle hooks?
created is called earlier, so it makes sense to trigger data fetching from API backend for example.
The `mounted()` Hook in VueVue calls the mounted() hook when your component is added to the DOM. It is most often used to send an HTTP request to fetch data that the component will then render. For example, the below Vue component uses the mounted() hook to make an HTTP request to the JSONPlaceholder API.
beforeCreate() This is the very first lifecycle hook that gets called in Vue JS, it gets called immediately after the Vue instance has been initialized.
beforeMount # Called right before the component is to be mounted. When this hook is called, the component has finished setting up its reactive state, but no DOM nodes have been created yet. It is about to execute its DOM render effect for the first time.
As shown in the Lifecycle Diagram of Vue instance. After Mounted Hook (which means we can access DOM), there is also beforeUpdate
and updated
hooks. These hooks can be used when data is changed. I think beforeUpdate
or update
hook can be used after getting data in created hook.
<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);
});
},
// here we can use beforeUpdate or updated hook instead of mounted
beforeUpdate() {
// get the ref="image" in my dom template
let imgs = this.$refs.image;
imgs.forEach((img) => {
// I do some stuff with imgs
});
}
}
I hope this helps. If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With