Pass data from parent to child component in vue.js

后端 未结 2 1935
一生所求
一生所求 2020-12-03 13:59

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

相关标签:
2条回答
  • 2020-12-03 14:26

    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>
    
    0 讨论(0)
  • 2020-12-03 14:27

    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
      }
    }
    
    0 讨论(0)
提交回复
热议问题