代码之家  ›  专栏  ›  技术社区  ›  jedi

Vuejs-将道具传递给子组件

  •  1
  • jedi  · 技术社区  · 6 年前

    我有一个要传递的父组件 props 到子组件。我用吸气剂从Vuex那里取回道具 userProfile 但是,在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>
    

    盖特斯JS

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

    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 回复  |  直到 6 年前
        1
  •  3
  •   Ana Liza Pandac    6 年前

    你的 userProfile getters 所以你应该用 mapGetters 而不是 mapState .

    变化 computed: mapState(['userProfile'])

    computed: mapGetters(['userProfile']) .

    推荐文章