我想知道如何使用props和检索将对象传递给子组件.我理解如何将其作为属性,但如何传递对象并从子组件中检索对象?当我从子组件使用this.props时,我得到未定义或错误消息. 父组件 tem
父组件
<template>
<div>
<my-component :v-bind="props"></my-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中提供的“同步”功能
https://vuejs.org/v2/guide/components.html#sync-Modifier
