Episode 22 of 44
Props
Pass data from parent to child components using props — the primary way to share data downward in the component tree.
Props
Components often need data from their parent. Props are the mechanism for passing data downward — from parent to child. The child declares which props it expects, and the parent provides the values.
Declaring Props
<!-- Child: NinjaCard.vue -->
<template>
<div class="card">
<h3>{{ ninja.name }}</h3>
<p>Rank: {{ ninja.rank }}</p>
</div>
</template>
<script>
export default {
name: 'NinjaCard',
props: ['ninja']
};
</script>
Passing Props from the Parent
<!-- Parent: Ninjas.vue -->
<template>
<div>
<NinjaCard v-for="ninja in ninjas" :key="ninja.name" :ninja="ninja" />
</div>
</template>
<script>
import NinjaCard from './NinjaCard.vue';
export default {
components: { NinjaCard },
data() {
return {
ninjas: [
{ name: 'Ryu', rank: 5 },
{ name: 'Ken', rank: 3 },
{ name: 'Yoshi', rank: 8 }
]
};
}
};
</script>
:ninja="ninja" binds the ninja prop to the current item in the loop. The child receives it and can use it in its template.
Props Validation
props: {
ninja: {
type: Object,
required: true
},
showRank: {
type: Boolean,
default: true
},
maxRank: {
type: Number,
default: 10,
validator(value) {
return value > 0 && value <= 100;
}
}
}
| Option | Purpose |
|---|---|
type | Expected data type (String, Number, Boolean, Object, Array, Function) |
required | Must the parent provide this prop? |
default | Default value if not provided |
validator | Custom validation function |
One-Way Data Flow
Props flow one way — from parent to child. A child should never mutate a prop directly. If you need to modify the data, either emit an event to the parent (covered in ep 24) or create a local data property initialized from the prop.
Key Takeaways
- Props pass data from parent to child components
- Declare props with an array of names or an object with validation
- Bind props with
:propName="value"in the parent's template - Props are read-only in the child — data flows one way (parent → child)