Vue 3中Props使用与渲染问题:为何Props显示为对象?
Vue3 Props传递异常问题解决
问题根源
- 父组件
Home传递props时误用了对象字面量语法::title={title}会被Vue解析为传递{title: title}这个对象,而子组件Title的titleprops定义的是字符串类型,所以UI显示出了对象内容{"title": "Home"}。 - 子组件
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
相关产品推荐
相关产品推荐

