defineProps 用于已注册子组件中声明可接收的 props,而非组件注册本身;注册分全局(app.component)和局部( 导入即注册)两种,注册后父组件才能传值,子组件再用 defineProps(数组/对象/TS 接口)声明接收规则。

defineProps 不用于组件注册,而是用于在已注册的子组件内部声明它能接收哪些来自父组件的属性(props)。组件注册和 props 声明是两个独立环节:注册决定“这个组件能不能被用”,而 defineProps 决定“这个组件能收什么数据”。
组件注册是前提,不是 defineProps 的职责
Vue 3 中组件注册分两种方式:
-
全局注册(在创建 app 时):
import { createApp } from 'vue' import MyButton from './components/MyButton.vue' const app = createApp(App) app.component('MyButton', MyButton) // 注册后,所有地方都能用 <mybutton></mybutton> -
局部注册(在父组件内):
<script setup> import MyButton from './components/MyButton.vue' // 不需要额外写 component 选项,<script setup> 中导入即自动局部注册 </script><template><mybutton title="提交" :disabled="true"></mybutton></template>
只有完成注册后,父组件才能使用该标签并传入属性——这时子组件才需要 defineProps 来接收。
defineProps 在子组件中声明接收规则
写在 <script setup></script> 里,无需 import,直接调用:
-
数组写法(只列名字)
适合快速开发或类型不敏感场景:const props = defineProps(['title', 'disabled']) // 模板中可直接用 {{ props.title }} -
对象写法(带类型、默认值、必填)
推荐用于正式项目:const props = defineProps({ title: { type: String, default: '按钮', required: true }, disabled: { type: Boolean, default: false } }) -
TypeScript 写法(编译期强校验)
更安全,IDE 支持好:interface Props { title: string disabled?: boolean } const props = defineProps<props>()</props>
注意:
-
props是响应式对象,但不可直接修改(如props.title = '新标题'会报警告); - 若需修改,应通过
emit通知父组件更新,或用v-model语法糖。
父组件怎么传?——按注册后的标签名用 attribute 传
假设子组件已注册为 ,父组件这样传:
<mybutton title="删除" :disabled="isDeleting"></mybutton>
- 普通 attribute(如
title="删除")→ 对应字符串 prop; - 带冒号的
:disabled→ 表示绑定表达式,传入布尔值、变量等。
子组件中 defineProps 声明了什么,父组件就传什么;没声明的属性会被忽略(除非启用 inheritAttrs: false + $attrs 手动处理)。
不复杂但容易忽略
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!










