Vue script setup 怎么使用 withDefaults 设置属性默认值

星婷君_8264

星婷君_8264

2026-10-23

898人浏览

原创

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

vue script setup 怎么使用 withdefaults 设置属性默认值

在 <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-composition-api-best-practices

Vue 3 组合式 API 与

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Vue 教程
Vue 教程

共42课时 | 17.2万人学习

国外Web开发全栈课程全集
国外Web开发全栈课程全集

共12课时 | 1.4万人学习

Vue.js 微实战--十天技能课堂
Vue.js 微实战--十天技能课堂

共18课时 | 1.7万人学习