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

Vue 3中Props使用与渲染问题:为何Props显示为对象?

Vue3 Props传递异常问题解决

问题根源

  1. 父组件Home传递props时误用了对象字面量语法::title={title}会被Vue解析为传递{title: title}这个对象,而子组件Title的title props定义的是字符串类型,所以UI显示出了对象内容{"title": "Home"}。
  2. 子组件Title的模板中,class={styling}存在同样问题,会把styling包装成对象传递给class属性,导致class失效。

正确实现代码

父组件Home修正版

<template>
    <div>
        <!-- 直接传递变量,无需额外包裹大括号 -->
        <Title :title="title" :styling="styling" />
    </div>
</template>

<script>
import Title from '../components/Title';

export default {
    name: 'Home',
    data() {
        return {
            title: 'Home',
            styling: 'text-center'
        }
    },
    components: { Title }
}
</script>

<style scoped>
</style>

子组件Title修正版

<template>
    <div>
        <!-- 使用:class绑定动态类名 -->
        <h5 :class="styling">{{ title }}</h5>
    </div>
</template>

<script>
export default {
    name: 'Title',
    props: { 
        title: {
            type: String,
            required: true
        },
        styling: {
            type: String
        }
     },
}
</script>

<style scoped>
</style>

关键知识点

  • Vue模板中,:(v-bind缩写)后的内容是JS表达式,直接写变量名就会传递变量的实际值,只有当你需要传递对象/数组时,才需要用大括号包裹。
  • 动态绑定class必须用:class语法,直接写class={变量}会被解析为对象,导致class属性异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 00:27:34