我正在使用 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 初始化代码包装在 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( ... )
...
}
})
关于每次页面重新启动时,Firebase.auth().currentUser 都会变为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62321683/