firebase - 每次页面重新启动时,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()
})
我希望用户不是每次重新启动页面时都登录一次
解决方案
这是因为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( ... )
...
}
})
推荐阅读
- python - 你能帮我减少我的代码执行时间吗?
- c - C 中的 unlink 函数是否也会释放内存?
- html - Shopify 适用于桌面/移动设备的不同集合横幅
- laravel - laravel 资源功能正常工作,但是当我手动使用它时不起作用
- javascript - 我的 Vue Js 应用程序会在每个文档更改时刷新
- c# - 如何避免在 csproj 中使用新的 PackageReference xml 标签复制引用的程序集
- php - laravel 引导方法在模型中不起作用
- powerapps - 如果 Power Apps 中的 json 中存在整数值,我无法将 json 绑定到集合
- javascript - 使用 javascript 或 jquery 以 html 形式上传默认图像
- python - Python:列表中的用户输入与第二个列表中的索引对齐,输出第二个列表元素