每次页面重新启动时,Firebase.auth().currentUser 都会变为 null

标签 firebase vue.js authentication firebase-authentication

我正在使用 Firebase 身份验证与 vue 应用程序 每次我登录用户后重新启动页面时,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()
})

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

最佳答案

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

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

解决此问题的一种方法是将 vue 初始化代码包装在 ma​​in.js(new Vue( ... )) 中,并使用 onAuthStateChanged 像这样:

let app;

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

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

关于每次页面重新启动时,Firebase.auth().currentUser 都会变为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62321683/

相关文章:

javascript - firebase 只获取 key 然后获取数据

ios - Firebase - 无法登录到 Facebook 身份验证

javascript - 在 HTML 表中显示从 firebase 数据库检索到的信息

vue.js - ionic vue 相册应用程序中的 `defineCustomElements(window);` 在哪里?

php - 无法在 Laravel 5.4 的 Blade 模板中使用 Auth::user()

android - 在 Android 中使用不同的 google-service.json 进行测试

typescript - ESLint:解析错误:意外的 token :

javascript - 如何为 VueJS 创建单条目 JS 文件

php - 在没有 session 的情况下验证系统 - 只有 cookie - 这是否相当安全?

php - Symfony2 : Check user authentication based on path