【问题标题】:Using Firebase user UID with vuefire manual binding将 Firebase 用户 UID 与 vuefire 手动绑定一起使用
【发布时间】:2017-07-03 08:39:20
【问题描述】:

在使用 Vue 和 Firebase 的简单 SPA 中,有两种路由:登录和聊天。

登录后,用户会被重定向到 Chat 路由,在该路由中使用 vuefire 的 $bindAsArray()created() 生命周期挂钩内手动完成 Firebase 数据库绑定。这是因为绑定需要 Firebase 身份验证分配的 uid 可用。

这工作正常,直到用户刷新页面。如果使用auth().currentUser 获取uid,则返回null。如果使用 auth().onAuthStateChanged() 观察者,Vue 会在 Firebase 数据库绑定完成之前尝试渲染组件。我错过了什么?

【问题讨论】:

    标签: firebase firebase-realtime-database vue.js firebase-authentication vuefire


    【解决方案1】:

    我遇到了这种情况,作为解决方法,我使用具有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>
    

    【讨论】:

    • 感谢您的回答。我喜欢这个主意,但你能解释一下最后的 else 块吗?
    • 我在代码上添加了一些cmets,如果您需要进一步解释,请告诉我
    • 我不知道 onAuthStateChanged() 的返回值。一切都清楚了,谢谢!
    猜你喜欢
    • 2019-10-08
    • 2017-11-15
    • 1970-01-01
    • 2018-01-19
    • 2018-03-12
    • 2012-11-12
    • 1970-01-01
    • 2019-01-17
    • 2018-04-08
    相关资源
    最近更新 更多