withDefaults 是 <script setup> 中的编译器宏,用于给基于类型声明的 defineProps 补默认值。它在编译期被展开为运行时的 default 选项,打包产物里不存在这个函数。
1. 基本用法
1 2 3 4 5 6 7 8 9 10 11
| interface Props { msg?: string count?: number labels?: string[] }
const props = withDefaults(defineProps<Props>(), { msg: 'hello', count: 0, labels: () => ['one', 'two'] })
|
签名(来自 @vue/runtime-core):
1 2 3 4
| withDefaults<T, BKeys extends keyof T, Defaults extends InferDefaults<T>>( props: DefineProps<T, BKeys>, defaults: Defaults ): PropsWithDefaults<T, Defaults, BKeys>
|
开发模式下上面的例子被编译为等价的运行时声明,而 props 声明位于 setup 之外的模块作用域:
1 2 3 4 5
| props: { msg: { type: String, required: false, default: 'hello' }, count: { type: Number, required: false, default: 0 }, labels: { type: Array, required: false, default: () => ['one', 'two'] } }
|
- 生产模式会丢掉大部分
type / required,只保留 { default: ... };Boolean 类型、以及带默认值的 Function 类型仍保留 type
- 第一参数必须是类型声明式的
defineProps,与运行时声明(数组/对象语法)组合会直接编译报错
- 宏无需 import,只能在
<script setup> 顶层使用
2. 默认值的书写规则
写法按 prop 类型分三种。规则来自运行时的 resolvePropValue:默认值是函数、且 prop 类型不是 Function 时,它被当作工厂函数调用。
| prop 类型 |
默认值写法 |
说明 |
| string / number / boolean / symbol |
直接给值 |
InferDefaults 只对这些原生类型接受字面量 |
| object / array / 自定义接口、类 |
工厂函数 () => ({ ... }) |
直接给值 TS 报错(该分支被推断为 never);绕过类型检查则所有实例共享同一引用 |
Function((...args) => R) |
直接给函数本身 |
prop 类型是 Function 时不走工厂调用,函数即默认值 |
1 2 3 4 5 6 7 8 9
| interface Props { user?: { name: string; age: number } onSubmit?: (value: string) => void }
const props = withDefaults(defineProps<Props>(), { user: () => ({ name: 'anon', age: 0 }), onSubmit: (value) => console.log(value) })
|
工厂函数接收 raw props 作为参数,可据此计算默认值,且每个实例只调用一次(结果缓存在 instance.propsDefaults):
1 2 3 4
| withDefaults(defineProps<{ type?: 'a' | 'b'; text?: string }>(), { text: (rawProps) => (rawProps.type === 'a' ? 'A' : 'B') })
|
其余三条规则:
- 默认值只在 prop 解析结果为
undefined 时生效——未传和显式传 undefined 都算;传 null 则保留 null
- 默认值表达式被原样内联进模块作用域的 props 声明,因此只能引用 import 进来的常量等模块级绑定,不能引用
<script setup> 内声明的变量(含 ref、computed)
- 类型声明本身不支持
validator,需要运行时自定义校验只能退回对象语法的 defineProps
3. 类型层面的效果
PropsWithDefaults 对返回类型做两件事:把出现在 defaults 里的 key 去掉可选标记(-?),并从其类型中剔除 undefined。
1 2 3 4 5 6 7 8 9 10
| interface Props { msg?: string count?: number }
const a = defineProps<Props>()
const b = withDefaults(defineProps<Props>(), { count: 0 })
|
- 默认值自身也受类型检查:值与 prop 类型不匹配、key 不在
Props 里,都是 TS 编译期报错
- 类型收紧只发生在类型层面;运行时 props 仍是只读响应式对象,
toRefs、模板中直用等行为不变
4. Boolean prop 的特殊 cast
Boolean 类型的 prop 有额外转换规则,而是否声明了默认值会改变这条规则:
1 2 3 4 5
| if (shouldCast) { if (isAbsent && !hasDefault) value = false else if (shouldCastTrue && (value === '' || value === hyphenate(key))) value = true }
|
1 2 3 4 5 6 7 8 9
| const p1 = defineProps<{ disabled?: boolean }>()
const p2 = withDefaults(defineProps<{ disabled?: boolean }>(), { disabled: true })
const p3 = withDefaults(defineProps<{ disabled?: boolean }>(), { disabled: undefined })
|
<Comp disabled />、<Comp disabled="" />、<Comp disabled="disabled" /> 都解析为 true
- 类型层面
defineProps<{ disabled?: boolean }>() 的 disabled 直接是必选 boolean,正是配合这条 cast 规则
5. 与 Vue 3.5 响应式解构的取舍
3.5 起解构 defineProps 的返回值保持响应式,默认值可直接用原生解构语法,官方推荐它取代 withDefaults(后者未废弃,3.4 及以下仍是唯一选择):
1
| const { msg = 'hello', labels = ['one', 'two'] } = defineProps<Props>()
|
| 维度 |
withDefaults |
响应式解构(3.5+) |
| 对象/数组默认值 |
必须手写工厂函数 |
编译器自动包成 () => (...) |
| 默认值与声明类型不匹配 |
TS 类型检查 |
编译期报错 does not match declared type |
| 拿到整体 props 对象 |
可以,支持 v-bind="props" 转发 |
不行,只有解构出的单个绑定 |
| 脚本中的访问方式 |
props.xxx |
直接用变量名,编译器改写为 props.xxx |
注意:两者不要混用。写成 const { msg } = withDefaults(defineProps<Props>(), { ... }) 时编译器不会注册解构绑定,响应式解构被禁用,msg 只是一次性快照,同时触发编译告警。需要整体转发 props 时,保留 withDefaults 并把返回值赋给 props。
6. 编译期约束与退化路径
| 场景 |
结果 |
第一参数不是 defineProps 调用 |
编译报错 withDefaults' first argument must be a defineProps call. |
| 配合运行时声明使用 |
编译报错 withDefaults can only be used with type-based defineProps declaration. |
| 缺少第二个参数 |
编译报错 The 2nd argument of withDefaults is required. |
| 第二参数不是静态对象字面量(变量、spread、非字面量计算键) |
不报错,产物退化为运行时 mergeDefaults(props, defaults) |
最后一行值得注意:退化成 mergeDefaults 后默认值在运行时合并,key 写错只会在开发环境打印 props default key "xxx" has no corresponding declaration.,而不是编译期失败;且 mergeDefaults 的实参整体被内联到模块作用域,作用域限制同 §2。