我是vue-router导航卫士的新手,所以我最近意识到我需要使用 beforeRouteUpdate
guard来重用组件,例如:从 /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
已经加载了下一个组件 .
1 回答
首先,您的操作应执行任何状态突变,例如将
user.get_user
设置为null
. 我添加了一块 Watch ;您的操作应该只在完成时解决 . 例如然后你的护卫队应该有类似的东西
为了防止错误尝试呈现
null
数据,请使用您的getter . 例如,说你的吸气剂是在您的组件中,您可以将其映射到计算属性...
然后在您的模板中,使用此逻辑有条件地呈现一些数据
这是vue-router guide for beforeRouteUpdate中建议的方法