🎁 Vue.js Props: The Gift-Giving System
Imagine you have a toy box. You want to share your favorite toys with your friends. But here’s the rule: you decide what toys to give, and your friends can only play with them—they can’t change them or give them back!
That’s exactly how Props work in Vue.js. Props are like gifts that a parent component gives to a child component.
🧸 What Are Props?
Think of a family:
- Parent = The mom or dad who has things to share
- Child = The kid who receives things
In Vue:
- Parent Component = Gives data (props)
- Child Component = Receives and uses data
<!-- Parent gives a gift -->
<ChildComponent gift="teddy bear" />
<!-- Child receives it -->
<template>
<p>I got a {{ gift }}!</p>
</template>
Simple: Props are how parent components talk to their children!
📝 Prop Declaration
Before a child can receive gifts, they need to tell everyone what gifts they expect. This is called declaring props.
The Simple Way (Array)
export default {
props: ['name', 'age', 'color']
}
Like saying: “I can receive name, age, and color!”
The Better Way (Object)
export default {
props: {
name: String,
age: Number,
color: String
}
}
Like saying: “I expect name to be words, age to be a number, and color to be words!”
Real Example:
<!-- Parent -->
<UserCard
name="Emma"
:age="8"
color="purple"
/>
<!-- UserCard.vue -->
<script>
export default {
props: {
name: String,
age: Number,
color: String
}
}
</script>
<template>
<div>
{{ name }} is {{ age }} years old.
Favorite color: {{ color }}
</div>
</template>
🏷️ Prop Types
Vue lets you specify what kind of gift you expect. This prevents mistakes!
| Type | What It Means | Example |
|---|---|---|
String |
Words | "Hello" |
Number |
Numbers | 42 |
Boolean |
Yes/No | true |
Array |
List of things | [1, 2, 3] |
Object |
Collection | {name: "Jo"} |
Function |
An action | () => {} |
props: {
title: String, // "My Story"
likes: Number, // 100
isActive: Boolean, // true
tags: Array, // ["fun", "cool"]
author: Object, // {name: "Sam"}
onClick: Function // () => alert("Hi")
}
Why Types Matter:
- Vue warns you if you send wrong types
- Makes your code easier to understand
- Catches bugs early!
⬇️ One-Way Data Flow
Here’s the most important rule:
Data flows DOWN like a waterfall. Never UP.
graph TD A["👨 Parent Component"] -->|props flow down| B["👧 Child Component"] B -.->|❌ Cannot send back| A
The Gift Rule
When your parent gives you a toy:
- ✅ You can play with it
- ✅ You can look at it
- ❌ You cannot change it
- ❌ You cannot give it back modified
// ❌ WRONG - Never do this!
props: ['count'],
methods: {
addOne() {
this.count++ // Vue will warn you!
}
}
// ✅ RIGHT - Make a copy first
props: ['count'],
data() {
return {
localCount: this.count
}
},
methods: {
addOne() {
this.localCount++ // This is okay!
}
}
Why This Rule?
- Keeps data organized
- Makes bugs easy to find
- Parent stays in control
✅ Prop Validation
Want to make sure gifts are exactly right? Use validation!
props: {
age: {
type: Number,
validator(value) {
// Age must be between 0 and 120
return value >= 0 && value <= 120
}
},
status: {
type: String,
validator(value) {
// Only these words allowed
return ['happy', 'sad', 'excited']
.includes(value)
}
}
}
What Happens If Validation Fails?
- Vue shows a warning in the console
- Your app still works, but you know something’s wrong
🚨 Required Props
Some gifts are must-haves. Mark them as required!
props: {
username: {
type: String,
required: true // Must be provided!
},
email: {
type: String,
required: true
},
nickname: String // Optional
}
If parent forgets a required prop:
<!-- Oops! Missing username -->
<UserProfile email="hi@example.com" />
<!-- Vue warns: Missing required prop "username" -->
Think of it like:
- You NEED a name to make a name tag
- You NEED ingredients to bake a cake
- Some things are just essential!
🎯 Default Prop Values
What if no gift arrives? Set a default!
props: {
color: {
type: String,
default: 'blue' // If not given, use blue
},
size: {
type: Number,
default: 100
},
tags: {
type: Array,
default() { // Arrays need a function
return ['general']
}
},
settings: {
type: Object,
default() { // Objects need a function
return { theme: 'light' }
}
}
}
Important Rule:
- Simple values (String, Number): Just write the default
- Complex values (Array, Object): Use a function that returns the default
Why a function for Arrays/Objects?
Each component needs its own copy. A function creates a fresh copy every time!
🔄 Boolean Casting
Booleans are special. Vue has magic shortcuts!
The Magic
<!-- These are the SAME! -->
<Button disabled />
<Button :disabled="true" />
<!-- These are also the SAME! -->
<Button />
<Button :disabled="false" />
Just writing the name = true
Not writing it = false
Full Example
// Button.vue
export default {
props: {
disabled: Boolean,
loading: Boolean,
outlined: Boolean
}
}
<!-- Parent using Button -->
<!-- All features ON -->
<Button disabled loading outlined />
<!-- Same as writing: -->
<Button
:disabled="true"
:loading="true"
:outlined="true"
/>
<!-- Only disabled ON -->
<Button disabled />
<!-- Everything OFF -->
<Button />
Multiple Types with Boolean
If prop can be multiple types, order matters!
props: {
// Boolean checked first
disabled: [Boolean, String]
}
<MyComponent disabled /> <!-- true (Boolean) -->
<MyComponent disabled="" /> <!-- true (Boolean) -->
<MyComponent disabled="yes" /> <!-- "yes" (String) -->
🎨 Complete Example
Let’s build a greeting card component!
// GreetingCard.vue
export default {
props: {
// Required - must have a name!
recipientName: {
type: String,
required: true
},
// With type
age: {
type: Number,
default: null
},
// With default
theme: {
type: String,
default: 'birthday'
},
// Boolean casting
animated: Boolean,
// With validation
mood: {
type: String,
validator(val) {
return ['happy', 'excited', 'grateful']
.includes(val)
},
default: 'happy'
},
// Array with default function
wishes: {
type: Array,
default() {
return ['Have a great day!']
}
}
}
}
Using it:
<!-- Simple -->
<GreetingCard recipientName="Alex" />
<!-- Full features -->
<GreetingCard
recipientName="Sam"
:age="10"
theme="celebration"
animated
mood="excited"
:wishes="['Stay awesome!', 'Dream big!']"
/>
🌟 Quick Summary
| Concept | What It Does |
|---|---|
| Props | Pass data from parent to child |
| Declaration | List what props you expect |
| Types | Say what kind of data (String, Number, etc.) |
| One-Way Flow | Data goes down only, never up |
| Validation | Custom rules for prop values |
| Required | Must be provided or Vue warns |
| Default | Fallback value if not given |
| Boolean Casting | Shortcuts for true/false |
🚀 You Did It!
Props are like a gift-giving system:
- Parent decides what to give
- Child declares what it can receive
- Data flows one direction (down)
- You can set rules and defaults
Now go build amazing components that talk to each other! 🎉
