【发布时间】:2017-12-25 12:51:17
【问题描述】:
我在我的 Vue/vuex/vue-router + Firebase 应用程序中遇到了一些难题。引导代码应该初始化 Firebase,以及 Vuex 中的登录用户(如果有):
new Vue({
el: '#app', router, store, template: '<App/>', components: { App },
beforeCreate() {
firebase.initializeApp(firebaseConfig)
// Because the code below is async, the app gets created before user is returned...
.auth().onAuthStateChanged(user => {
this.$store.commit('syncAuthUser', user) // this executes too late...
})
}
})
在我的路线中,我有
{ path: '/home', name: 'Home', component: Home, meta: { requiresAuth: true } }
还有
router.beforeEach((to, from, next) => {
let authUser = store.getters.authUser // this is not set just yet...
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!authUser) {
next('signin') // /home will always hit here...
}
next()
}
else {
next()
}
})
问题
正如 cmets 中所提到的,应用程序获取经过身份验证的用户为时已晚。所以,当你在登录时去/home时,应用程序会在路由中运行beforeEachcheck ...并且用户实例暂时不可用,所以它会认为你没有登录, 事实上你是(从我的计算属性中可以清楚地看出,稍后会正确更新)。
问题
那么,我该如何更改我的代码,以便仅在 Firebase 返回用户并且将该用户传递到 Vuex 商店之后才初始化 Vue 应用程序?如果我做错了什么,请告诉我。
尝试
- 我试过"unsubscribe" approach;然而,它的问题是
onAuthStateChanged只会被触发一次。因此,如果我将重要的this.$store.commit('syncAuthUser', user)放在那里,那么该代码只会在创建应用程序时执行,而不是在用户注销时执行。 - 我还尝试了更好的方法here。我确实为我工作,但我觉得将
onAuthStateChanged包裹在另一个Promise中很糟糕,肯定有更好的方法;另外,将 auth 用户初始化登录名放在路由文件中似乎是错误的。
【问题讨论】:
-
嗨,我在使用 Firebase 时也遇到了这个问题。我使用 Angular,但遇到了同样的问题。最后,我认为可靠的方法是在组件中等待用户身份验证。是的,observables 是通往这里的道路。
标签: firebase vue.js firebase-authentication vuejs2 vuex