Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass data from parent to child component in vue.js

Tags:

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!

like image 321
Trung Tran Avatar asked Aug 29 '16 05:08

Trung Tran


People also ask

How do I pass data from parent to child component in Vue?

component' you need to define the props passed in the child component. you need to call getCurrentUser() when the parent component initialises.

How do you pass a parent component to a child?

To pass data from child to parent component in React:Pass a function as a prop to the Child component. Call the function in the Child component and pass the data as arguments. Access the data in the function in the Parent .

What are the methods of passing data between a parent and a child component?

Embed the child component to the parent component. Pass the props to the child component as an argument while embedding it to the parent component. In the child component, access the data variable value by writing the name or variable only.


1 Answers

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   } } 
like image 95
pkawiak Avatar answered Sep 19 '22 18:09

pkawiak