Vuejs 2 Passing prop object to child component and retrieving

Viewed 33561

I was wondering how to pass an object to a child component using props and retrieving. I understand how to do it as attributes but how to pass an object and retrieve the object from the child component? When I use this.props from the child component I get undefined or an error message.

Parent component

 <template>
        <div>
        <child-component :v-bind="props"></child-component>     
        </div>
    </template>

<script>
import ChildComponent from "ChildComponent.vue";

export default {
    name: 'ParentComponent',
    mounted() {

    },
     props: {
       firstname: 'UserFirstName',
       lastname: 'UserLastName'
       foo:'bar'
    },
    components: {
    ChildComponent
    },
    methods: {

      }
}
</script>

<style scoped>
</style>

Child component

<script>
<template>
   <div>
   </div>
</template>
export default {
    name: 'ChildComponent',
    mounted() {
    console.log(this.props)
  }  
}
</script>
3 Answers

Yo can use v-bind="object" to pass an object as props to child component, besides you can access props in template using $props, therefore the answer is:

Parent Component:

<template>
  <div>
    <child-component v-bind="$props"></child-component>     
  </div>
</template>

<script>
  import ChildComponent from "ChildComponent.vue";

  export default {
    name: 'ParentComponent',
    props: {
      firstname: 'UserFirstName',
      lastname: 'UserLastName'
      foo:'bar'
    },
    components: {
      ChildComponent
    }
  }
</script>

Child Component:

<template>
  <div>
  </div>
</template>
<script>
export default {
  name: 'ChildComponent',
  props: ['firstname', 'lastname', 'foo'],
  mounted() {
    console.log(this.$props)
  }  
}
</script>

Here's a simple solution for passing many props as an object into a component

Parent Component:

<template>
  <div>
    <!-- different ways to pass in props -->
    <my-component v-bind="props"></my-component>     
    <my-component :firstname="props.firstname" :lastname="props.lastname" :foo="props.foo">
    </my-component>     
  </div>
</template>

<script>
  import ChildComponent from "ChildComponent.vue";

  export default {
    name: 'ParentComponent',
    props: {
      firstname: 'UserFirstName',
      lastname: 'UserLastName'
      foo:'bar'
    },
    components: {
      ChildComponent
    }
  }
</script>

Child Component:

<template>
  <div>
  </div>
</template>
<script>
export default {
  name: 'ChildComponent',
  props: ['firstname', 'lastname', 'foo'],
  mounted() {
    console.log(this.props)
  }  
}
</script>
Related