mounted method is fired before data loaded - VueJS
Since the this.imgs.query()
call is async, your mounted
hook is being called before the then
handler is setting this.imgs
(which I'm assuming is being bound with v-for
to an element in your template with an attribute ref="image"
). So, even though the component has been mounted to the DOM, the $refs
have not been set up yet.
I would make a method to "do some stuff with imgs" and then call that method in a $nextTick
callback in the then
handler of the async call. The callback passed to $nextTick
will be "executed after the next DOM update cycle", meaning the $refs
will be set up at that point.
<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>
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.