在vue.js

时间:2016-08-29 05:52:30

标签: components vue.js

我正在尝试将数据从父组件传递到子组件。但是,我试图传递的数据在子组件中保持打印为空白。我的代码:

Profile.js(父组件)

<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>

ProfileForm.js(子组件)

<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>

注意 - 我的user是通过我的getCurrentUser()方法加载的...有人可以帮忙吗?

提前致谢!

2 个答案:

答案 0 :(得分:27)

要通过道具传递数据,您必须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
  }
}

答案 1 :(得分:4)

请注意以下几点:

  • 您错过了详细说明“ Vue.component”的行
  • 您需要定义在子组件中传递的道具
  • 您需要在父组件初始化时调用getCurrentUser()

父项...

<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>

子组件...

<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>