Pass data from parent to child component in vue.js
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
}
}
Please note the following:
- you missed out the line detailing 'Vue.component'
- you need to define the props passed in the child component
- you need to call getCurrentUser() when the parent component initialises
Parent Component...
<template>
<div class="container">
<profile-form :user="user"></profile-form>
</div>
</template>
<script>
import ProfileForm from './ProfileForm'
Vue.component('profile-form', ProfileForm);
export default {
data: function () {
return {
user: ''
}
},
methods: {
getCurrentUser: function () {
auth.getCurrentUser(function(person) {
this.user = person
})
},
created: function() {
this.getCurrentUser();
},
}
</script>
Child Component...
<template>
<div class="container">
<h1>Profile Form Component</h1>
</div>
</template>
<script>
export default {
props: ['user'],
created: function () {
console.log('user data from parent component:')
console.log(this.user) //prints out an empty string
},
}
</script>