【深入学习Vue丨第一篇】Props 完全指南
前言
在 Vue.js 中,Props 是组件之间数据传递的重要机制。简单来说,Props 是父组件向子组件传递数据的一种方式,类似于函数的参数,让组件能够接收外部传入的数据。
第一章:Props 基础概念
1.1 为什么需要 Props?
想象一个场景:我们需要创建多个用户卡片,每个卡片显示不同的用户信息。如果没有 Props,我们需要为每个用户创建单独的组件:
<!-- 没有使用 Props - 重复代码 -->
<template><div><div class="user-card"><h3>张三</h3><p>年龄:25</p><p>职业:前端工程师</p></div><div class="user-card"><h3>李四</h3><p>年龄:30</p><p>职业:后端工程师</p></div></div>
</template>
使用 Props 后,我们可以创建一个可复用的组件:
<!-- 使用 Props - 可复用组件 -->
<!-- UserCard.vue -->
<template><div class="user-card"><h3>{{ name }}</h3><p>年龄:{{ age }}</p><p>职业:{{ job }}</p></div>
</template><script>
export default {props: ['name', 'age', 'job']
}
</script><!-- 父组件中使用 -->
<template><div><user-card name="张三" :age="25" job="前端工程师" /><user-card name="李四" :age="30" job="后端工程师" /></div>
</template>
1.2 Props 的工作流程

第二章:Props 的声明和使用
2.1 基本的 Props 声明
数组形式的声明(简单但不推荐)
<script>
export default {props: ['title', 'content', 'author']
}
</script>
对象形式的声明(推荐)
<script>
export default {props: {title: String,content: String,author: String,likes: Number,isPublished: Boolean,tags: Array,metadata: Object,callback: Function}
}
</script>
2.2 各种数据类型的 Props 示例
<!-- ChildComponent.vue -->
<template><div class="demo-component"><h3>{{ title }}</h3><p>内容:{{ content }}</p><p>点赞数:{{ likes }}</p><p>是否发布:{{ isPublished ? '是' : '否' }}</p><p>标签:{{ tags.join(', ') }}</p><button @click="handleClick">点击我</button></div>
</template><script>
export default {props: {// 字符串类型title: String,content: String,// 数字类型likes: Number,// 布尔类型isPublished: Boolean,// 数组类型tags: Array,// 对象类型userInfo: Object,// 函数类型onAction: Function},methods: {handleClick() {if (this.onAction) {this.onAction('按钮被点击了!');}}}
}
</script>
<!-- ParentComponent.vue -->
<template><div><child-componenttitle="欢迎学习 Vue Props"content="这是一个关于 Props 的教程":likes="42":is-published="true":tags="['Vue', 'JavaScript', '前端']":user-info="{ name: '张三', age: 25 }":on-action="handleAction"/></div>
</template><script>
import ChildComponent from './ChildComponent.vue'export default {components: {ChildComponent},methods: {handleAction(message) {console.log('收到子组件的消息:', message)alert(message)}}
}
</script>
第三章:Props 高级配置
3.1 Props 验证
Props 验证可以确保传入的数据符合预期格式,提高代码的健壮性。
<script>
export default {props: {// 基础的类型检查title: String,// 多个可能的类型flexibleProp: [String, Number],// 必填项requiredProp: {type: String,required: true},// 默认值count: {type: Number,default: 0},// 带有默认值的对象config: {type: Object,default: () => ({color: 'blue',size: 'medium'})},// 自定义验证函数age: {type: Number,validator: function(value) {return value >= 0 && value <= 150}},// 复杂的默认函数items: {type: Array,default: () => []}}
}
</script>
