实现vue中的prop
定义 Props
在 Vue 组件中,通过 props 选项定义组件可以接收的属性。支持数组或对象形式定义。数组形式仅列出属性名,对象形式可以进一步指定类型、默认值等配置。
// 数组形式
props: ['title', 'content']
// 对象形式
props: {
title: String,
content: {
type: String,
default: 'Default content',
required: true
}
}
传递 Props
在父组件中,通过类似 HTML 属性的方式传递数据给子组件。可以使用静态值或动态绑定(v-bind)。
<ChildComponent title="Static Title" :content="dynamicContent" />
类型验证
通过对象形式的 props 可以指定类型验证,支持多种原生构造函数(如 String、Number、Boolean、Array、Object、Date、Function、Symbol)。
props: {
age: Number,
isValid: Boolean,
tags: Array,
user: Object
}
默认值与必填
通过 default 设置默认值,required 标记属性是否必填。默认值为对象或数组时,需使用工厂函数返回。
props: {
count: {
type: Number,
default: 0
},
items: {
type: Array,
default: () => []
},
name: {
type: String,
required: true
}
}
自定义验证
通过 validator 函数实现自定义逻辑验证,返回 true 或 false。
props: {
score: {
validator(value) {
return value >= 0 && value <= 100
}
}
}
单向数据流
Vue 的 props 遵循单向数据流原则,子组件不应直接修改 props 的值。需通过事件或本地数据副本处理。

export default {
props: ['initialValue'],
data() {
return {
localValue: this.initialValue
}
}
}






