Vue.js Vuex Firebase - 无法从商店获取用户

Vue.js Vuex Firebase - Cannot get user from store

在我的路由器中,我有一个 beforeEach 守卫来检查受保护的页面.. 当我显示商店状态时,我可以看到有一个用户(绑定到 Firebase)但我无法获取它,甚至无法显示它...

router.beforeEach((to, from, next) => {
  console.log('ROUTER from: ', from, ' to: ', to, '  next: ', next)
  if (to.matched.some(record => record.meta.requiresAuth)) {
    console.log('protected page')
    console.log('store state: ', store.state)
    console.log('store state user: ', store.state.user)
    if (!store.state.user || !store.state.user.emailVerified || store.state.user.isAnonymous) {
      // console.log('ROUTER auth user: ', store.state.user)
      next({
        path: '/signin'
      })
    } else {
      next()
    }
  } else {
    // console.log('ROUTER no auth: ', to)
    next()
  }
})

console.log 来自 Chrome 开发工具的输出

确保用户是Auth,如果你使用vue-cli,你可以在你main.js中使用firebase auth的方法onAuthStateChanged()。看例子:

在你main.js firebase 初始化后

// Initialize Firebase
    let config = {
       apiKey: "you_app_generated_key",
       authDomain: "youapp-randomkey.firebaseapp.com",
       databaseURL: "https://youapp-randomkey.firebaseio.com",
       projectId: "youapp-randomkey",
       storageBucket: "gs://youapp-randomkey.appspot.com/",
    };
    firebase.initializeApp(config);

    //If the event onAuthStateChanged() is emited
    //You can can verify if the user is auth or not.
    //If he isn't you can set null for the user.

    firebase.auth().onAuthStateChanged((user) => {

        if (user) {

            this.$store.dispatch('setUser', user) //set the User

        } else {

            this.$store.dispatch('setUser', null) //set null because he is notauth
        }

    })


    }
})

现在,在项目的任何部分,您都可以验证您的状态中是否有用户。

如果有User,要显示它,就看你需要显示什么用户属性了。

当需要显示或获取用户时:姓名、电子邮件和照片。我愿意:

let user = state.user
let user_id: user.uid
let user_name: user.displayName,
let user_photo: user.photoURL

.

对不起我的英语。