Vuejs 2将prop对象传递给子组件并进行检索 [英] Vuejs 2 Passing prop object to child component and retrieving
问题描述
我想知道如何使用props和检索将对象传递给子组件。我了解如何将其作为属性,但是如何传递对象并从子组件中检索对象?当我从子组件中使用this.props时,会得到未定义或错误消息。
I was wondering how to pass an object to a child component using props and retrieving. I understand how to do it as attributes but how to pass an object and retrieve the object from the child component? When I use this.props from the child component I get undefined or an error message.
父组件
<template>
<div>
<child-component :v-bind="props"></child-component>
</div>
</template>
<script>
import ChildComponent from "ChildComponent.vue";
export default {
name: 'ParentComponent',
mounted() {
},
props: {
firstname: 'UserFirstName',
lastname: 'UserLastName'
foo:'bar'
},
components: {
ChildComponent
},
methods: {
}
}
</script>
<style scoped>
</style>
儿童部分
<script>
<template>
<div>
</div>
</template>
export default {
name: 'ChildComponent',
mounted() {
console.log(this.props)
}
}
</script>
推荐答案
很简单:
父组件:
<template>
<div>
<my-component :propObj="anObject"></my-component>
</div>
</template>
<script>
import ChildComponent from "ChildComponent.vue";
export default {
name: 'ParentComponent',
mounted() { },
props: {
anObject: Object
},
components: {
ChildComponent
},
}
</script>
<style scoped>
</style>
子组件:
export default {
props: {
// type, required and default are optional, you can reduce it to 'options: Object'
propObj: { type: Object, required: false, default: {"test": "wow"}},
}
}
这应该可行!
还请查看道具文档:
https://vuejs.org/v2/guide/components.html#Props
如果要按照注释中的指示将数据从子级发送到父级,则必须使用事件或查看同步功能在2.3 +
If you want to sent data from the child to the parent as was already pointed in the comments you have to use events or take a look at 'sync' feature which is available in 2.3 +
https://vuejs.org/v2/guide/components.html#sync-Modifier
这篇关于Vuejs 2将prop对象传递给子组件并进行检索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!