1

VueとFirebaseを使用したシンプルなSPAには、ログインとチャットという2つのルートがあります。FireFoxユーザUIDとvuefireのマニュアルバインディングの使用

ログイン時に、ユーザはcreated()ライフサイクルフック内のvuefireの$bindAsArray()を使用してFirebaseデータベースバインディングが手動で行われるチャットルートにリダイレクトされます。これは、バインディングでFirebase認証によって割り当てられたuidが使用可能である必要があるためです。

これは、ユーザーがページを更新するまで問題なく動作します。 auth().currentUserを使用してuidを取得すると、nullが返されます。 auth().onAuthStateChanged()ウォッチャが使用されている場合、VueはFirebaseデータベースのバインディングが完了する前にコンポーネントのレンダリングを試みます。私は何が欠けていますか?

答えて

3

回避策としてUIDがnullの場合は、UIDというプロパティを持つコンポーネントラッパーを使用します。UIDがnullの場合は、待機メッセージ/アニメーションを表示して元のコンポーネントを表示します。

私の本当のシナリオはここ(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> 
+0

のおかげのようになります。もう少し複雑です。私はそのアイデアが気に入っていますが、最後のelseブロックについて説明してください。 – TheCorwoodRep

+0

コードにいくつかのコメントを追加しました。さらなる説明が必要な場合はお知らせください。 – AldoRomo88

+0

onAuthStateChanged()の戻り値についてはわかりませんでした。すべてがクリア、ありがとう! – TheCorwoodRep

関連する問題