Vue 的 props 是组件之间传递数据的一种方式,允许父组件向子组件传递数据。以下是基于 Vue 官方文档的详细说明。
基本概念
- Props 声明:一个组件需要显式声明它所接受的 props,这样 Vue 才能知道外部传入的哪些是 props,哪些是透传 attribute。
- 用途:props 可以用于接收父组件传递的数据,例如字符串、数字、对象等,并在子组件中使用。
声明方式
在 Vue 3 中,使用 <script setup> 时,可以通过 defineProps() 宏来声明 props:
const props = defineProps(['car']);
-
defineProps()返回一个对象,包含所有传入的props。 -
除了字符串数组,还可以使用对象形式声明,以指定类型校验:
const props = defineProps({
car: String
}); -
对象形式可以作为组件文档,并在类型错误时抛出警告。1
使用示例
在父组件中,可以通过自定义属性传递数据:
<BlogPost title="Blogging with Vue" :fontSize="8" />
在子组件中,直接使用 props:
<template>
<div :style="{ fontSize: props.fontSize + 'em' }">
{{ props.title }}
</div>
</template>
- props 会自动暴露给模板,无需额外处理。
类型校验与默认值
-
类型校验:可以使用构造函数(如 Number、String)或对象形式指定类型。例如:
defineProps({
propA: Number,
propB: [String, Number] // 多种可能类型
})
默认值 :通过 default 选项设置默认值:
defineProps({
fontSize: { type: Number, default: 16 }
})
必传校验 :设置 required: true 表示必传:
defineProps({
title: { type: String, required: true }
})
- 如果未传递布尔类型
prop,默认值为false;其他类型为undefined。
响应式与解构
-
props是响应式的,访问props.foo会跟踪依赖。在解构时,Vue 会自动添加props.前缀(Vue 3.5+):const { title, fontSize } = props // 等同于 props.title 和 props.fontSize
-
解构后,
props仍保持响应式,但需注意不要直接修改props(遵循单向数据流)。
高级特性
-
自定义校验函数:可以定义验证逻辑:
defineProps({
propG: {
validator(value) {
return ['success', 'warning', 'danger'].includes(value)
}
}
}) -
透传 attribute :未声明的
props会作为透传 attribute 应用于子组件根元素,但可通过defineEmits避免误用。
注意事项
props是单向数据流,子组件不应直接修改props,而应通过事件通知父组件。- 在 TypeScript 中,可以为
props标注类型,提升开发体验。
通过以上方式,props 能有效实现组件间的数据传递和类型安全。如果需要更复杂的交互,可结合 emits 事件机制。
demo:
<!-- 父子组件传值 父 -->
<template>
<div class="father">
<h4>父亲有辆汽车: {{car}}</h4>
<child :car="car"></child>
</div>
<BlogPost title="Blogging with Vue" :fontSize="10" />
</template>
<script setup lang="ts">
import { ref } from 'vue';
import child from './child.vue';
import BlogPost from './BlogPost.vue';
const car = ref('奔驰');
</script>
<style scoped>
.father {
border: 1px solid green;
padding: 10px;
}
</style>
<!-- 父子组件传参 子 -->
<template>
<div class="child">
<h4>儿子有一玩具: {{toy}}</h4>
<h4>父亲给的车: {{car}}</h4>
</div>
</template>
<script setup lang="ts">
const props = defineProps(['car']);
const toy = '奥特曼';
</script>
<style scoped>
.child {
border: 1px solid yellow;
padding: 10px;
}
</style>
<!-- 父子组件传值 BlogPost -->
<template>
<div :style="{ fontSize: props.fontSize + 'em' }">
{{ props.title }}
</div>
</template>
<script setup lang="ts">
const props = defineProps({
title: String,
fontSize: {
type: Number,
default: 1
}
});
</script>