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

时间:2018-03-29 10:53:48

标签: firebase vue.js vuex

在我的路由器中,我有一个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()
  }
})

Chrome开发工具的console.log输出

console.log

1 个答案:

答案 0 :(得分:0)

如果您使用的是vue-cli,请确保用户是Auth,您可以在onAuthStateChanged()使用firebase auth的main.js方法。参见示例:

在firebase inicialization之后

在你main.js

// 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
        }

    })


    }
})

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

如果有用户,要显示它,它取决于您需要显示的用户道具。

需要显示或获取用户时:姓名,电子邮件和照片。我这样做:

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

抱歉我的英文。