firebase - 使用带有 vuefire 手动绑定(bind)的 Firebase 用户 UID

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

在使用 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/

相关文章:

javascript - 组件外部元素上的 v-model

javascript - 有没有办法在 TypeScript 类定义中转义和使用保留字?

swift - 在函数外部获取 let 值

swift 3 和火力地堡 : Retrieve auto id value from snapshot

javascript - <transition-group> 如何与 Vue.components 一起工作?

javascript - 简单 for 循环与 >> 运算符之间的区别

firebase - 在 webpack vue 项目中添加 firebase 配置变量的位置

firebase - 如何导出Firebase分析数据

firebase - 如何在flutter中添加尝试功能?

ios - 数据服务错误未解决