【发布时间】:2019-02-03 19:09:09
【问题描述】:
我是 vue-router 导航守卫的新手,所以我最近意识到我需要使用beforeRouteUpdate 守卫来重用组件,例如:从/foo/1 转到/foo/2
但是,在来到/foo/1 时,我通过 axios 调用从数据库中提取数据,在转到 /foo/2 之前,我需要通过 axios 调用再次提取新数据。
这是我面临的问题,导航守卫beforeRouteUpdate 在我从 axios 调用加载数据之前加载组件/foo/2,因此我的一些变量为空。
如何让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已经加载了下一个组件。
【问题讨论】:
-
你的代码是什么样的?你关注the official guide了吗?
-
我用我的代码更新了我的问题。至于官方指南,我已经浏览了 beforeRouteUpdate 的其他示例以了解其正确使用方法,但无法解决问题@Phil
-
编辑问题时不要忘记点击“保存编辑”按钮
-
对不起,我的错。我在评论@Phil 后更新了问题
-
您应该只通过突变更新状态,而不是直接更新状态(通过
Vue.set或其他方式)
标签: javascript vuejs2 axios vuex vue-router