我的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()
}
})
问题
正如评论中所提到的,该应用程序得到了经过身份验证的用户太晚了 . 因此,当您在登录时转到 /home
时,应用程序将在路由中运行 beforeEach
检查...并且用户实例尚未可用,因此它会认为您尚未登录,而实际上您是(从我的计算属性中可以清楚地看到,稍后会对其进行适当更新) .
问题
那么,如何更改我的代码,以便仅在Firebase返回用户之后以及在该用户传递到Vuex商店之后才初始化Vue应用程序?如果我做错了什么,请告诉我 .
尝试
-
我试过"unsubscribe" approach;但问题是
onAuthStateChanged
只会被触发一次 . 因此,如果我将关键的this.$store.commit('syncAuthUser', user)
放在那里,那么该代码只会在创建应用程序时执行,而不是在用户注销时执行 . -
我也尝试过更好的方法here . 我确实为我工作过,但我觉得在另一个
Promise
包裹onAuthStateChanged
,肯定有一个更好的方法;另外,将auth用户初始化登录放在routes文件中似乎是错误的 .
1 回答
示例
./App.vue
./store.js(突变)
概述
LifeCycle
此示例使用Vue的
created:
生命周期钩子 . 在created:
中,我们使用auth.onAuthStateChanged
来启动事件监听器 . 您的应用现在正在侦听来自firebase的身份验证更改 .只要Firebase注意到身份验证状态更改,就会返回
user
对象 . 使用其属性和方法进行身份验证和授权 .properties :
user.emailVerfied
方法:
user.getIdToken()
TL; DR
使用Firebase
onAuthStateChanged
时,必须实现Observable
和Subscriptions
对象 . RxJS Observable是异步的,如promise
,它将帮助您等待Firebase的auth响应 .请参阅documentation中的 first 参数,
nextOrObserver
:Observable设计模式(即异步,推送,多播)记录在案here .