You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue向SFC传递Props时对象属性转为DIV元素属性问题

问题:Vue2中v-bind传递对象到子组件时属性意外挂载到DOM元素

我正尝试将从Strapi接口获取的对象传递给子组件,当前使用Nuxt Bridge与Vue 2.6.14版本。

父组件通过fetch请求获取数据:

<script>
export default {
    async fetch() {
        this.featured = await fetch(
            'http://localhost:1337/api/getFeature',
        ).then((res) => res.json());
        this.feed = await fetch(
            'http://localhost:1337/api/getFeed'
        ).then((res) => res.json());
    },
    data(){
        return {
            featured: {},
            feed: []
        }
    },
}
</script>

父组件中使用<Feature v-bind="featured"/>传递数据,子组件定义Props为:

<script>
export default {
    props: {
        featured: Object,
    }
}
</script>

问题在于,传递的对象属性最终变成了子组件第一个DIV标签的元素属性:

<div title="Apple pie apple pie tootsie roll liquorice tiramisu topping" lede="Gummies lemon drops tootsie roll cake jelly beans candy cotton candy. Apple pie chocolate bar bear claw icing candy chocolate bar jelly pie" url="https://ik.imagekit.io/nnydigital/strapi/bryam_blanco_n_XKW_Ln8y9q_E_unsplash_44c4203534_M_Kx22_N6x_YD_abf84d3bbd_Mo5JvpCD3.jpg" created="Wed Jun 29 2022 10:38:07 GMT-0400 (Eastern Daylight Time)" updated="Wed Jun 29 2022 10:38:08 GMT-0400 (Eastern Daylight Time)" published="Wed Jun 29 2022 10:38:08 GMT-0400 (Eastern Daylight Time)">

但如果使用<Feature :title="featured.title" />单独传递属性则正常。请问我哪里操作有误?


原因分析

<Feature v-bind="featured"/>的写法会把featured对象里的所有顶层属性作为单独的props传递给子组件,但你的子组件仅声明了featured这一个props,并未定义title、lede等零散属性。

在Vue2中,组件接收到未在props中声明的属性时,会默认将这些属性透传到组件的根DOM元素上,这就是你看到属性出现在子组件第一个div标签上的原因。

解决方法

有两种可行方案:

方案一:传递完整对象作为单个props

修改父组件的传递方式,明确将featured对象作为名为featured的props传递:

<Feature :featured="featured" />

这样子组件就能正确接收完整的featured对象,不会触发属性透传。

方案二:子组件声明对应独立props

如果子组件需要单独使用title、lede等属性,直接在props中逐个声明:

<script>
export default {
    props: {
        title: String,
        lede: String,
        url: String,
        created: String,
        updated: String,
        published: String
    }
}
</script>

此时父组件用<Feature v-bind="featured"/>就能正常传递属性,且不会透传到根DOM元素。


内容的提问来源于stack exchange,提问作者James Nobles

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 09:06:23