defineProps 是 Vue 3 <script setup> 中声明 props 的标准方式,支持字符串数组(无类型校验)、泛型接口(TS 类型安全)和对象配置(运行时校验/默认值),需注意响应式解构限制与不可直接修改。

在 Vue 3 的 <script setup> 中,defineProps 是声明和接收父组件传入属性(props)的标准方式。它无需导入、自动响应式、支持类型推导和运行时校验,是组合式 API 下最简洁可靠的 props 声明手段。
基础用法:字符串数组形式
适合快速开发或类型要求不高的场景,只声明 prop 名称,不提供类型检查或默认值:
- 写法:
const props = defineProps(['title', 'disabled']) - 模板中直接使用:
{{ props.title }} - JS 中读取:
console.log(props.title) - 注意:无法设置默认值、必填校验或类型约束
TypeScript 推荐写法:泛型接口
搭配 lang="ts" 使用接口定义,获得完整类型提示、IDE 补全和编译期检查:
Vue 3 组合式 API 与 最佳实践,涵盖代码组织、useXxx 模式、组合式函数设计、Store 集成、响应式优化及功能抽取。
- 先定义接口:
interface Props { title: string; count?: number; onChange: (val: string) => void; } - 再调用:
const props = defineProps<Props>() - 可选属性用
?标记(如count?) - 函数类型需明确参数与返回值(如
onChange),避免运行时类型错误
运行时校验:对象形式声明
适用于需要默认值、必填控制、类型断言或自定义验证的生产环境:
立即学习“前端免费学习笔记(深入)”;
- 写法示例:
defineProps({ title: { type: String, default: '默认标题' }, count: { type: Number, required: true }, tags: { type: Array as PropType<string[]>, default: () => [] } }) -
type支持原生构造函数(String、Number等)或PropType(TS 场景下数组/对象需显式标注) -
default若为引用类型(如数组、对象),必须是函数形式,防止状态共享 -
required: true未传时会在开发环境触发警告 -
validator可传入函数,例如validator: (val) => ['success', 'error'].includes(val)
使用注意事项
props 天然响应式,但有几处容易出错的地方需留意:
- 不能直接解构 props(如
const { title } = props),会丢失响应性;应改用toRefs(props)或computed(() => props.title) - 子组件不可修改 props,否则控制台报错;如需“双向绑定”,应配合
defineEmits和v-model语法糖 - 在组合式函数中使用 props 值时,若传入的是普通值(如字符串),需用
watch或computed订阅变化,否则不会自动更新

















