Pass data from parent to child component in vue.js

Trung Tran picture Trung Tran · Aug 29, 2016 · Viewed 57.4k times · Source

I am trying to pass data from a parent to a child component. However, the data I am trying to pass keeps printing out as blank in the child component. My code:

In Profile.js (Parent component)

<template>

    <div class="container">
        <profile-form :user ="user"></profile-form>
    </div>

</template>

<script>

import ProfileForm from './ProfileForm'

module.exports = {

    data: function () {
        return {
            user: ''
        }
    },

   methods: {

    getCurrentUser: function () {
        var self = this
        auth.getCurrentUser(function(person) {
            self.user = person
        })
    },

}

</script>

In ProfileForm.js (Child component)

<template>

<div class="container">
    <h1>Profile Form Component</h1>
</div>  

</template>


<script>


module.exports = {


  created: function () {
    console.log('user data from parent component:')
    console.log(this.user) //prints out an empty string
  },


}

</script>

Note - my user is loaded via my getCurrentUser() method... Can someone help?

Thanks in advance!

Answer

pkawiak picture pkawiak · Aug 29, 2016

To pass data via props, you have to declare them in child component:

module.exports = {   
  props: ['user'],

  created: function () {
    console.log('user data from parent component:')
    console.log(this.user) //prints out an empty string
  }
}