Props & Emits
Parent-Child Communication
In Vue, components communicate through a clear pattern: props down, events up. This means:
- Parent components pass data to children via props
- Child components notify parents of changes via emits
This unidirectional data flow makes your application easier to understand and debug.
Props
Props are custom attributes you can register on a component. When a value is passed to a prop attribute, it becomes a property on that component instance.
<script setup>
// Declare props
const props = defineProps({
initialValue: {
type: Number,
default: 0
}
})
</script>
Props Validation
You can specify prop types, default values, required status, and custom validators:
defineProps({
count: {
type: Number,
required: true,
validator: (value) => value >= 0
}
})
Emits
Emits allow child components to communicate with their parent. You should declare all emitted events using defineEmits:
<script setup>
const emit = defineEmits(['update', 'reset'])
function handleChange(newValue) {
emit('update', newValue)
}
</script>
v-model on Components
The v-model directive can be used on components for two-way binding. It's a shorthand for passing a prop and listening to an event:
<!-- Parent -->
<Counter v-model="count" />
<!-- Is equivalent to -->
<Counter :modelValue="count" @update:modelValue="count = $event" />
Challenge
Create a Counter component that:
- Accepts an
initialValueprop (number, default: 0) - Displays the current count
- Has increment (+) and decrement (-) buttons
- Emits an
updateevent when the count changes - Passes the new count value with the event
In app.vue, use the Counter component and:
- Pass
initialValueas a prop - Listen to the
updateevent - Display the count received from the child
Tip: Remember to declare your emits using defineEmits() for better type safety and documentation.
If you get stuck, you can check the solution by clicking the button below.
Props and emits are fundamental to Vue component communication. Master this pattern before moving on to more advanced techniques like provide/inject.