Components & Props
Props allow parent components to pass read-only data down to child components, establishing clear interfaces for reusable UI elements.
1 defineProps and type validation
Vue validates props at runtime to catch data bugs early:
- defineProps(): Macro used in the Composition API to declare component props (does not need to be imported).
- Read-Only Bound: Props form a one-way down data binding. Child components must not mutate prop values directly.
- Type Checkers: Define props with explicit types, defaults, and required constraints for runtime validation.
2 Declaring and validating props
Let's check how to declare and validate props in a child component:
Vue — Child Component (Props)
<template>
<div class="user-card">
<h4>Name: {{ name }}</h4>
<p>Status: {{ isActive ? 'Active' : 'Offline' }}</p>
</div>
</template>
<script setup>
// Declare and validate props using compile macro
defineProps({
name: {
type: String,
required: true
},
isActive: {
type: Boolean,
default: false
}
});
</script>
3 Code Challenge
Challenge: Write a component class
ArticleCard that accepts props for title, readTimeMinutes (as a Number), and category (with a default value of 'General').