How to Define Props in Vue: Syntax and Examples
In Vue, you define props by declaring a
props option in your component, which lists the expected properties from the parent. Props can be defined as an array of strings or as an object with type and default values for better validation.Syntax
Props are declared inside the component's props option. You can use a simple array of strings for prop names or an object to specify types and default values.
- Array syntax: List prop names as strings.
- Object syntax: Define each prop with type, default, and other options.
javascript
export default { props: ['title', 'count'] } // or with object syntax export default { props: { title: String, count: { type: Number, default: 0 } } }
Example
This example shows a child component receiving props title and count from its parent and displaying them.
vue
<template>
<div>
<h2>{{ title }}</h2>
<p>Count: {{ count }}</p>
</div>
</template>
<script>
export default {
props: {
title: String,
count: {
type: Number,
default: 0
}
}
}
</script>Output
<h2>My Title</h2>
<p>Count: 5</p>
Common Pitfalls
Common mistakes include:
- Not declaring props in the child component, so passed data is ignored.
- Passing wrong types without validation, causing unexpected behavior.
- Mutating props inside the child, which is against Vue's one-way data flow.
Always declare props and treat them as read-only inside the child.
javascript
/* Wrong: Mutating a prop directly */ export default { props: ['count'], mounted() { this.count = 10; // ❌ This will cause a warning } } /* Right: Use a local data copy to modify */ export default { props: ['count'], data() { return { localCount: this.count }; }, methods: { increment() { this.localCount++; } } }
Quick Reference
| Prop Definition | Description |
|---|---|
| props: ['name'] | Declare props as an array of strings |
| props: { name: String } | Declare props with type validation |
| props: { count: { type: Number, default: 0 } } | Prop with type and default value |
| props: { active: Boolean } | Boolean prop, defaults to false if not passed |
| props: { items: Array } | Array prop type declaration |
Key Takeaways
Always declare props in the child component using the props option.
Use object syntax to specify prop types and default values for better validation.
Props are read-only inside the child; do not mutate them directly.
You can define props as simple strings or detailed objects depending on your needs.
Passing props correctly enables clear data flow from parent to child components.