【问题标题】:VueJS - Passing props to a child componentVueJS - 将道具传递给子组件
【发布时间】:2019-01-07 14:33:06
【问题描述】:

我有一个父组件,我想将props 传递给子组件。我使用 getter 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: ''
        }
      };
    },
   }

我做错了什么?

【问题讨论】:

  • 您是否异步获取用户数据?因为如果是这种情况,您的userProfile getter 最初可能会返回undefined,直到异步方法返回。一个简单的解决方法是指定一个空对象作为 profile 属性的默认值:default: () =&gt; ({})
  • 不,我将用户对象存储在 VueX 状态:state: { auth: { user: { here is the user object }}}

标签: vue.js


【解决方案1】:

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

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

computed: mapGetters(['userProfile'])

【讨论】:

    猜你喜欢
    • 2020-11-23
    • 2018-07-07
    • 2017-12-23
    • 1970-01-01
    • 2018-12-12
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    • 2017-10-02
    相关资源
    最近更新 更多