1

在帶有Vue和Firebase的簡單SPA中,有兩種路由:登錄和聊天。使用帶有vuefire手動綁定的Firebase用戶UID

登錄後,用戶將被重定向到Chat路由,其中​​使用vuefire的$bindAsArray()created()生命週期鉤子內手動完成Firebase數據庫綁定。這是因爲綁定需要由Firebase身份驗證分配的uid可用。

這工作正常,直到用戶刷新頁面。如果auth().currentUser用於獲取uid,則它返回空值。如果使用了auth().onAuthStateChanged()觀察器,則Vue將在Firebase數據庫綁定完成之前嘗試呈現組件。我錯過了什麼?

回答

3

我碰到過這種情況,因爲我使用的組件包裝器具有UID作爲屬性,如果UID爲null顯示等待消息/動畫else顯示您的原始組件。

我真正的情況是有點複雜,在這裏(火力,路由,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> 
+0

感謝您的回答。我喜歡這個主意,但是你能解釋一下最後的其他區塊嗎? – TheCorwoodRep

+0

我已經添加了一些關於代碼的評論,如果您需要進一步的解釋,請告知我 – AldoRomo88

+0

我不知道onAuthStateChanged()的返回值。一切都清楚了,謝謝! – TheCorwoodRep