一、基本该概念
Props 是父组件向子组件传递数据的桥梁,子组件通过定义 props 接收父组件的数据
二、定义方式
1、简单类型定义(数组形式)
javascript
// 子组件定义
props: ['name', 'age']
// 父组件使用
<child-component :name="userName" :age="userAge" />
2、对象类型定义(推荐)
javascript
props: {
name: {
type: String,
default: 'Guest',
required: true
},
age: {
type: Number,
validator: (value) => value >= 0
}
}
三、类型验证
支持的类型:
- String
- Number
- Boolean
- Array
- Object
- Date
- Function
- Symbol
四、默认值设置
javascript
// 基础类型默认值
age: {
type: Number,
default: 0
}
// 对象/数组默认值(需通过工厂函数返回)
userInfo: {
type: Object,
default: () => ({ name: 'Guest' })
}
五、必传验证
javascript
name: {
type: String,
required: true
}
六、自定义验证
javascript
email: {
type: String,
validator: (val) => {
const emailRegex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/
return emailRegex.test(val)
}
}
七、使用场景
1、动态数据绑定
javascript
<child-component :count="currentCount" />
2、单向数据流
- 子组件不能直接修改 props
- 需通过 $emit 触发父组件方法更新
3、接收任意类型
javascript
content: null // 不指定类型,接收任意类型
八、注意事项
1、驼峰命名转换
javascript
// 子组件定义
props: { myProp: String }
// 父组件使用(HTML标签需转为短横线命名)
<child-component my-prop="value" />
2、数组/对象解构
javascript
// 子组件使用解构
const { name, age } = props
3、监听props变化
javascript
watch: {
propsData: {
handler(newVal, oldVal) {
// 处理变化
},
deep: true
}
}
九、最佳实践
- props 命名建议使用驼峰式
- 复杂对象使用对象形式定义
- 始终设置合理的默认值
- 必要时添加类型验证和自定义校验
- 避免在子组件直接修改 props 值
示例代码:
父组件:
javascript
<template>
<user-card
:user-info="user"
:is-vip="isMember"
@update:user-info="handleUpdate"
/>
</template>
<script>
import UserCard from '@/components/UserCard.vue'
export default {
components: { UserCard },
data() {
return {
user: { name: 'John', age: 30 },
isMember: true
}
},
methods: {
handleUpdate(newUser) {
this.user = newUser
}
}
}
</script>
子组件:
javascript
<template>
<view class="card">
<text>{{ userInfo.name }}</text>
<text v-if="isVip">VIP Member</text>
</view>
</template>
<script>
export default {
props: {
userInfo: {
type: Object,
required: true,
default: () => ({})
},
isVip: {
type: Boolean,
default: false
}
}
}
</script>