VueJS is a new technology for me, and I'm currently working on a component that needs to retrieve data from an API before loading the corresponding route. The component should only load once the data is fetched. Additionally, after the component is created, I need to call another API that uses the data obtained from the first API as input. Below is the script for my component:
export default {
name: 'login',
data () {
return {
categories: []
}
},
created () {
// it gives length = 0 but it should have been categories.length
console.log(this.categories.length);
// Call getImage method
loginService.getImage(this.categories.length)
.then(res => {
console.log('Images fetched');
})
},
beforeRouteEnter (to, from, next) {
loginService.getCategories().then((res) => {
next(vm => {
vm.categories = res.data.categories;
});
}, (error) => {
console.log('Error: ', error);
next(error);
})
},
methods: {}
}
I attempted to use the mounted
hook, but it didn't work as expected. However, when I used a watch
on the categories
property and called the fetch image method, it worked. I'm unsure if using watchers is the best approach in this scenario. Any suggestions?