将数据从父组件传递到vue.js中的子组件

Tru*_*ran 16 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>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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

提前致谢!

pka*_*iak 27

要通过props传递数据,您必须在子组件中声明它们:

module.exports = {   
  props: ['user'],

  created: function () {
    console.log('user data from parent component:')
    console.log(this.user) //prints out an empty string
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 这可以附加到孩子的“数据”对象中的另一个元素吗? (2认同)

oma*_*ari 5

请注意以下事项:

  • 您错过了详细介绍“ 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>
Run Code Online (Sandbox Code Playgroud)

子组件...

<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>
Run Code Online (Sandbox Code Playgroud)