如何使用v-bind绑定对象类型props?问题排查与规范实现
Vue中v-bind绑定对象类型Props的正确用法
问题场景
父组件定义了如下对象:
const post = { id: 1, title: 'My Journey with Vue' }
尝试通过v-bind="post"传递给子组件,但子组件中{{ post }}显示为空。已知单独绑定props的方式,需要明确如何规范使用v-bind绑定对象类型props。
现有父组件(parent.vue)代码:
<template> <img alt="Vue logo" src="./assets/logo.png"> <component :is="HelloWorld" :msg="m" v-bind="post"/> </template> <script> import HelloWorld from './components/HelloWorld.vue' export default { name: 'App', components: { HelloWorld } } </script> <script setup> const post = { id: 1, title: 'My Journey with Vue' } </script>
现有子组件代码:
<template> <div class="hello"> msg:{{msg}} <br/> posts:{{post}} </div> </template> <script> export default { name: 'HelloWorld', props: { msg: String, post: Object, } } </script>
问题原因
v-bind="post"的作用是将post对象的每个属性单独作为props传递给子组件,也就是实际传递了id和title两个独立的props,而非把整个post对象作为名为post的props传递。子组件中声明的post props并未接收到任何值,因此显示为空。
两种解决方案
方案1:传递整个对象作为单个Props
如果需要把post对象作为一个整体传递给子组件的post props,只需在父组件中明确绑定:post="post":
修改后的父组件模板:
<template> <img alt="Vue logo" src="./assets/logo.png"> <component :is="HelloWorld" :msg="m" :post="post"/> </template>
子组件的props声明无需修改,此时{{ post }}就能正常显示完整的post对象。
方案2:保持批量传递,子组件接收对应单个Props
如果想继续使用v-bind="post"批量传递属性,子组件需要声明对象中对应的单个props(即id和title),而非post:
修改后的子组件代码:
<template> <div class="hello"> msg:{{msg}} <br/> postId:{{id}} <br/> postTitle:{{title}} </div> </template> <script> export default { name: 'HelloWorld', props: { msg: String, id: Number, title: String } } </script>
如果需要在子组件中组合成post对象,可通过计算属性实现:
<template> <div class="hello"> msg:{{msg}} <br/> posts:{{ postObj }} </div> </template> <script> export default { name: 'HelloWorld', props: { msg: String, id: Number, title: String }, computed: { postObj() { return { id: this.id, title: this.title } } } } </script>
补充说明
官方文档中「Binding Multiple Properties Using an Object」章节的示例对应的是方案2,即利用v-bind将对象的每个属性映射为独立的props传递。若需传递整个对象作为单个props,必须显式绑定:propName="object"。
内容的提问来源于stack exchange,提问作者Amrmsmb
相关产品推荐
相关产品推荐

