首页 > 解决方案 > 每次页面重新启动时,Firebase.auth().currentUser 都会变为 null

问题描述

我在 vue 应用程序中使用 firebase 身份验证每次登录用户后重新启动页面时 currentUser 变为 null

  firebase.auth().signInWithEmailAndPassword(this.email, this.password)
    .then(() => this.$router.push({name: 'Home'}))
    .catch(err => this.feedback = err.message)

并在 Vue 路由器中

 router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    let user = firebase.auth().currentUser
    if (!user) {
      next({name: 'Login'})
    } else next()
  } else next()
})

我希望用户不是每次重新启动页面时都登录一次

标签: firebasevue.jsauthenticationfirebase-authentication

解决方案


这是因为beforeEach在 firebase 完全完成初始化之前执行。

您可以使用onAuthStateChanged观察者确保 vue 应用程序仅在 firebase 完全初始化后才被初始化。

修复它的一种方法是将 vue 初始化代码包装在main.js ( new Vue( ... )) 中,onAuthStateChanged如下所示:

let app;

...
firebase.initializeApp( ... );

firebase.auth().onAuthStateChanged(() => {
  if (!app) { // ignore reinitializing if already init (when signing out/login)
    new Vue( ... )
    ...
  }
})

推荐阅读