在 vue.js 中将数据从父组件传递到子组件
2016-08-29
112793
我尝试将数据从父组件传递到子组件。但是,我尝试传递的数据在子组件中一直打印为空白。我的代码:
在
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()
方法加载的...有人可以帮忙吗?
提前致谢!
3个回答
要通过 props 传递数据,你必须 在子组件中声明它们 :
module.exports = {
props: ['user'],
created: function () {
console.log('user data from parent component:')
console.log(this.user) //prints out an empty string
}
}
pkawiak
2016-08-29
请注意以下几点:
- 您漏掉了详细说明“Vue.component”的行
- 您需要定义在子组件中传递的 props
- 您需要在父组件初始化时调用 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>
omarjebari
2018-07-23
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>
Manoj Shukla
2020-12-25