withdefaults 是专为 defineprops 设计的编译时宏,用于 typescript 类型声明的 props 设置默认值,需配合泛型类型使用,引用类型默认值必须用函数返回以避免共享。

在 <script setup></script> 中,withDefaults 是专为 defineProps 设计的编译时宏,用于给 TypeScript 类型声明的 Props 设置默认值。它不需导入,直接调用,且只在类型声明方式下生效。
必须配合 defineProps 的类型声明使用
withDefaults 不能和运行时声明(如 defineProps({ msg: String }))混用,否则会报错。它只接受泛型接口或内联类型作为第一个参数:
- 正确写法:用
()这类类型标注 - 错误写法:同时写类型 + 运行时配置,比如
defineProps<...>({ msg: String })</...>
基本语法结构清晰
格式固定为:
const props = withDefaults(defineProps<yourtype>(), { /* 默认值对象 */ })</yourtype>
例如:
<script setup lang="ts">
interface Props {
title: string
count?: number
theme?: 'light' | 'dark'
}
const props = withDefaults(defineProps<Props>(), {
count: 0,
theme: 'light'
})
</script>
这里 title 没设默认值,说明它是必传项;count 和 theme 有默认值,父组件不传时自动生效。
vue-composition-api-best-practices
Vue 3 组合式 API 与
热门下载
相关下载
精品课程
相关推荐
/
热门推荐
/
最新课程
最新文章
