在使用 Vue 和 Firebase 的简单 SPA 中,有两条路线:登录和聊天。
登录后,用户将被重定向到 Chat 路由,在该路由中使用 vuefire 的 $bindAsArray()
在 created()
生命周期内手动完成 Firebase 数据库绑定(bind)钩。这是因为绑定(bind)需要 Firebase 身份验证分配的 uid
可用。
这工作正常,直到用户刷新页面。如果使用auth().currentUser
获取uid
,则返回null。如果使用 auth().onAuthStateChanged()
观察器,Vue 会尝试在 Firebase 数据库绑定(bind)完成之前渲染组件。我错过了什么?
最佳答案
我遇到过这种情况,作为解决方法,我使用具有 UID
作为属性的组件包装器,如果 UID
为空,则显示等待消息/动画,否则显示您的原始组件.
我的真实场景稍微复杂一些(firebase、路由、vuex),但基本上包装器组件应该与此类似
<template>
<component :is="CurrentComponent" />
</template>
<script>
import App from './App';
import WaitingAnimation from './WaitingAnimation';
export default {
data() {
return {
Uid: null,
}
},
computed: {
CurrentComponent() {
return this.Uid == null ? WaitingAnimation : App;
}
}
beforeMount() {
//While Firebase is initializing `Firebase.auth().currentUser` will be null
let currentUser = Firebase.auth().currentUser;
//Check currentUser in case you previously initialize Firebase somewhere else
if (currentUser) {
//if currentUser is ready we just finish here
this.Uid = currentUser.uid;
} else {
// if currentUser isn't ready we need to listen for changes
// onAuthStateChanged takes a functions as callback and also return a function
// to stop listening for changes
let authListenerUnsuscribe = Firebase.auth().onAuthStateChanged(user => {
//onAuthStateChanged can pass null when logout
if (user) {
this.Uid = user.uid;
authListenerUnsuscribe(); //Stop listening for changes
}
});
}
}
}
</script>
关于firebase - 使用带有 vuefire 手动绑定(bind)的 Firebase 用户 UID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42236618/