VueJS-将道具传递给子组件

时间:2019-01-07 14:33:06

标签: vue.js

我有一个父组件,我想将props传递给子组件。我用吸气剂userProfile从VueX检索道具 并像这样传递它们,但是在editAccount组件中,我收到错误"TypeError: Cannot read property 'first_name' of undefined"

<template>
  <EditAccount :profile="userProfile" :submit="saveUserProfile"/>
</template>
<script>
  import { mapState, mapActions } from 'vuex'
  import EditAccount from './editAccount.vue'

  export default {
    components: { EditAccount },
    computed: mapState(['userProfile']),
    methods: mapActions(['saveUserProfile'])
  }
</script>

getters.js

export default {
  userProfile: state => {
    return state.auth.user
  }
};

store.js

state: {
    auth: {
      user: {}
    }
}

我确认,在VueJS控制台中,我有getter返回的用户对象。该对象是已通过身份验证并已登录的用户。

user:Object
  avatar:Object
  created_at:"2018-12-05"
  email:"fake_email@example.com"
  facebook_url:"https://some_url"
  first_name:"Firstname"
  hourly_rate:"10"
  id:4
  last_name:"lastname"
  linked_in_url:null
  phone_number:123123123
  rides_count:27
  twitter_url:"https://some_url"
  updated_at:"asdasd"
  username:"asdasd"

组件表格

<form @submit.prevent="onSubmit">
    <div class="input">
      <label for="first_name">First name</label>
      <input
              type="text"
              id="first_name"
              v-model="accountInfo.firstName">
    </div>
</form>

export default {
    props: {
      profile: {
        type: Object,
      },
    },
    data() {
      return {
        accountInfo: {
          firstName: this.profile.first_name,
          lastName: this.profile.last_name,
          phoneNumber: this.profile.phone_number,
          facebookUrl: this.profile.facebook_url,
          twitterUrl: this.profile.twitter_url,
          linkedInUrl: this.profile.linked_in_url,
          hourlyRate: this.profile.hourly_rate,
          avatar: ''
        }
      };
    },
   }

我在做什么错了?

1 个答案:

答案 0 :(得分:3)

您的userProfilegetters的一部分,因此您应该使用mapGetters而不是mapState

更改computed: mapState(['userProfile'])

computed: mapGetters(['userProfile'])