我是vue-router导航卫士的新手,所以我最近意识到我需要使用beforeRouteUpdate
后卫来重复使用组件,例如:从/foo/1
到/foo/2
然而,在来到/foo/1
时,我通过axios调用从数据库中提取数据,在进入/foo/2
之前,我需要通过axios调用再次提取新数据。
这是我遇到的问题,导航警卫beforeRouteUpdate
在我的数据从axios调用加载之前加载组件/foo/2
,因此我在一些变量中得到null。
如何使beforeRouteUpdate
等待加载下一个组件,以便从axios调用加载我的所有数据?
至于我的代码,它看起来像这样:
beforeRouteUpdate (to, from, next) {
Vue.set(this.$store.state.user, 'get_user', null)
this.$store.dispatch(OTHER_PROFILE_GET, to.params.id).then(resp => {
console.log(resp);
if(this.$store.getters.is_user_loaded) {
next()
} else {
this.$store.watch((state, getters) => getters.is_user_loaded, () =>
{
if(this.$store.getters.is_user_loaded) {
console.log(this.$store.state.user.get_user);
console.log('comes here');
next()
}
})
}
})
},
为了进一步解释我的代码,我在我的组件中调用了这个方法,所以当我从/user/1
转到/user/2
时,我发送了一个Vuex动作,它发出了一个axios调用来获取新的配置文件细节但是在axios调用完成之前并加载数据在Vuex状态下,beforeRouteUpdate
已经加载了下一个组件。
首先,你的行动应该执行任何状态突变,例如将user.get_user
设置为null
。我也不确定你为什么要加一块手表;您的操作应该只在完成时解决。例如
actions: {
[OTHER_PROFILE_GET] ({ commit }, id) {
commit('clearUserGetUser') // sets state.user.get_user to null or something
return axios.get(`/some/other/profile/${encodeURIComponent(id)}`).then(res => {
commit('setSomeStateData', res.data) // mutate whatever needs to be set
})
}
}
然后你的护卫队应该有类似的东西
beforeRouteUpdate (to, from, next) {
this.$store.dispatch(OTHER_PROFILE_GET, to.params.id).then(next)
}
为了防止错误尝试渲染null
数据,请使用您的getter。例如,说你的吸气剂是
getters: {
is_user_loaded (state) {
return !!state.user.get_user
}
}
在您的组件中,您可以将其映射到计算属性...
computed: {
isUserLoaded () {
return this.$store.getters.is_user_loaded // or use the mapGetters helper
},
user () {
return this.$store.state.user.get_user // or use the mapState helper
}
}
然后在您的模板中,使用此逻辑有条件地呈现一些数据
<div v-if="isUserLoaded">
Hello {{user}}
</div>
<div v-else>
Loading...
</div>