Pass data from parent to child component in vue.js Pass data from parent to child component in vue.js vue.js vue.js

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>


Vue.component("parent-component", {        props: ["title"],        data() {          return {            todos: this.title,          };        },        provide() {          return {            todoLength: this.todos,          };        },        template: "<div></slot> <slot></slot></div>",      });      Vue.component("child-component", {        inject: ["todoLength"],        template: "<div>{{this.todoLength}} </div>",      });      var APP = new Vue({        el: "#app",        data: {          message: "You loaded this page on " + new Date().toLocaleString(),        },        component: ["parent-component", "child-component"],      });
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script><div id="app">      <parent-component title="Hello from parent component to child component">        <child-component></child-component>      </parent-component>    </div>