Javascript VueJS:在加载组件之前和之后获取数据
我是VueJS新手,正在处理一个组件,希望在加载相应的路由之前从API获取一些数据;只有这样,组件才能加载。创建组件后,我必须调用另一个API,该API将从第一个API获得的数据作为输入。以下是我的组件脚本:Javascript VueJS:在加载组件之前和之后获取数据,javascript,vue.js,vuejs2,vue-component,Javascript,Vue.js,Vuejs2,Vue Component,我是VueJS新手,正在处理一个组件,希望在加载相应的路由之前从API获取一些数据;只有这样,组件才能加载。创建组件后,我必须调用另一个API,该API将从第一个API获得的数据作为输入。以下是我的组件脚本: export default { name: 'login', data () { return { categories: [] } }, created () { // it gives length = 0 but it shou
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: {}
}
我尝试使用
挂载的
钩子,但它不起作用。但是,如果我观察categories
属性并调用fetch image方法,它就会工作。我不认为使用观察者是最好的方法。有什么想法吗?将您的调用移动到一个方法中以获取更多信息,然后从下一个调用该方法
export default {
name: 'login',
data () {
return {
categories: []
}
},
beforeRouteEnter (to, from, next) {
loginService.getCategories().then((res) => {
next(vm => {
vm.categories = res.data.categories;
vm.getMoreStuff()
});
}, (error) => {
console.log('Error: ', error);
next(error);
})
},
methods: {
getMoreStuff(){
console.log(this.categories.length);
// Call getImage method
loginService.getImage(this.categories.length)
.then(res => {
console.log('Images fetched');
})
}
}
}
或者,在getCategories的回调中执行此操作
loginService.getCategories()
.then(res => {
vm.categories = res.data.categories;
loginService.getImage(vm.categories.length)
.then(res => //handle images then call next())
})
.catch(err => //handle err)
或者,如果您使用的是处理异步/等待的预编译器
async beforeRouteEnter(to, from, next){
try{
const categoryResponse = await loginService.getCategories()
const categories = categoryResponse.data.categories
const imageResponse= await loginService.getImage(categories.length)
next(vm => {
vm.categories = categories
vm.images = imageResponse.data.images
})
} catch(err){
//handle err
}
}
我很感激你的回答,但我仍然不清楚为什么它在创建的
钩子中也不起作用。