const props = defineProps({
title: {
type: String,
required: true
},
count: {
type: Number,
default: 0
}
})
const props = withDefaults(defineProps<{
title?: string
count?: number
}>(), {
title: '默认标题',
count: 1
})
const { title, count } = defineProps<{ title: string, count: number }>()
const props = defineProps<{ title: string, count: number }>()
const { title, count } = toRefs(props)
const props = defineProps({
title: {
type: String as PropType<string>, // 写了类型
default: 'Hello' // 又写默认值
}
})
type Size = 'sm' | 'md' | 'lg'
withDefaults(defineProps<{
size?: Size
}>(), {
size: 'md'
})
const emit = defineEmits<{
(e: 'submit', value: number): void
(e: 'cancel'): void
}>()
这样写出的组件,输入(props)+ 输出(emit)都具备契约,可以被任何 IDE 精确识别。
✔ defineProps 写法决定你能不能使用 Volar 的类型推导
很多人发现 <MyComponent :title="xx" /> 里没有类型提示,大概率是你组件没有正确写 defineProps 的泛型。保持结构清晰,是让 IDE 吃得饱的唯一方式。
🚀 小结:defineProps 不只是 props,它是组件健壮性的开端
确思路是:在 TypeScript 项目中,尽可能采用 defineProps<T>() + withDefaults() 写法,做到类型明确、默认值清晰、响应式安全。
📌 怎么判断你是否“真的会用 defineProps”?
- ❌ 你写了 defineProps 但 props 解构不响应
- ❌ 你写 default 写得很痛苦
- ❌ 你项目里 props 写法风格混乱
- ❌ 你的组件在 IDE 中没有 props 自动补全
✅ 如果你能做到:
- 使用泛型 +
withDefaults
- 保持 props 和 emits 的契约完整
- 清晰地类型提示和响应性解构
那恭喜你,是真的理解了 Vue3 的组件心智模型。
如果对您有所帮助,欢迎您点个关注,我会定时更新技术文档,大家一起讨论学习,一起进步。