How to get the user info to the “data” part of the app in vue.js?

浪子不回头ぞ 提交于 2019-12-30 13:01:25

问题


Would you happen to know how to set the user to the currentUser? I am using vuefire and firebase. The user.uid is returning undefined.

 <td v-if="(building['key'] && building['key'].child('ownerId')) == user.uid">
            <p >{{building['.key']}} + {{user.uid}}</p>
</td>

this is the rest of my code:

import firebase,{ db, usersRef, buildingsRef } from '../firebase-config';
import { store } from '../store/store';

export default {

  firebase() { 
    // from my understanding this just gives me a quick access to the Refs and a short nomenclature
    return { 
    users: usersRef,  
    buildings: buildingsRef, 
    }
  },
  name: 'buildings',
  data () {
    return {
      user: "",
      building: {
        name: '',
        address: '',
        comments: '',
        ownerId: '',
      },
    }
  },

I am trying to do it through the store in the beforeCreate hook:

  beforeCreate () {
       this.$store.dispatch('setUser');
       let user = this.$store.getters.getUser;
       console.log(user); // this works!!!
      this.$set(this.user, 'uid', user.uid )
  }   
},

If instead I set the user in create hook like this:

  created () {
       this.$store.dispatch('setUser');
       let user = this.$store.getters.getUser;
       console.log(user); // this works!!!
      this.$set(this.user, 'uid', user.uid )
    } 

I get this error:


回答1:


In Vue, the state (aka data properties) is initialized between the beforeCreate and created hooks.

So any change you do to data in beforeCreate is lost.

Change your hook to created

created() {                         // changed this line
  this.$store.dispatch('setUser');
  let user = this.$store.getters.getUser;
  console.log(user); // this works!!!
  this.$set(this.user, 'uid', user.uid)
}


来源:https://stackoverflow.com/questions/49760478/how-to-get-the-user-info-to-the-data-part-of-the-app-in-vue-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!