Vue3 Script Setup嵌套对象类型Prop默认值不生效问题排查
问题原因
你遇到的问题是:Props接口通过继承获取的可选属性,Vue的withDefaults未能正确识别并应用默认值,导致未传入title时,props.title为undefined,最终getText函数返回"null"。
解决方案
这里提供几种可行的修复方式:
方案1:直接定义Props接口,避免继承
去掉接口继承,直接在Props中声明所有属性,让Vue能正确识别需要设置默认值的Prop:
<script setup lang="ts"> interface LocaleText { text: string; single?: boolean; count?: number; params?: any; } interface Filter { title?: LocaleText; items?: string[]; } // 直接定义Props,不继承Title interface Props { title?: LocaleText; filters?: Filter[]; } interface Data { selectedStatus: string; } const props = withDefaults(defineProps<Props>(), { title: () => ({ text: "ExampleText" }), filters: () => [], }); function getText(text?: LocaleText): string | undefined | null { return text?.text ?? "null"; } </script> <template> <div> Example: {{ getText(props.title) }} </div> </template>
方案2:在Props接口中重新声明继承的属性
如果需要保留接口继承,可以在Props中重新声明title属性,确保Vue识别该属性并应用默认值:
interface Props extends Title { filters?: Filter[]; title?: LocaleText; // 重新声明title属性 }
方案3:使用运行时Prop定义(明确指定类型和默认值)
改用运行时的Prop定义方式,直接指定类型和默认值,彻底避免接口继承带来的识别问题:
<script setup lang="ts"> interface LocaleText { text: string; single?: boolean; count?: number; params?: any; } interface Filter { title?: LocaleText; items?: string[]; } interface Props { title?: LocaleText; filters?: Filter[]; } // 明确指定每个Prop的类型和默认值 const props = withDefaults(defineProps({ title: { type: Object as () => LocaleText, default: () => ({ text: "ExampleText" }) }, filters: { type: Array as () => Filter[], default: () => [] } }), {}); function getText(text?: LocaleText): string | undefined | null { return text?.text ?? "null"; } </script> <template> <div> Example: {{ getText(props.title) }} </div> </template>
内容的提问来源于stack exchange,提问作者Vinicius Andrade
相关产品推荐
相关产品推荐

