【问题标题】:Firebase.auth().currentUser turns to null every time the page restarts每次页面重新启动时,Firebase.auth().currentUser 都会变为 null
【发布时间】:2020-09-30 22:29:51
【问题描述】:

我在 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()
})

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

【问题讨论】:

    标签: firebase vue.js authentication firebase-authentication


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-06
      • 2021-09-16
      • 2018-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-20
      相关资源
      最近更新 更多