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:

  1. Accepts an initialValue prop (number, default: 0)
  2. Displays the current count
  3. Has increment (+) and decrement (-) buttons
  4. Emits an update event when the count changes
  5. Passes the new count value with the event

In app.vue, use the Counter component and:

  • Pass initialValue as a prop
  • Listen to the update event
  • 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.

Vue Components
Components are reusable pieces of UI that have their own logic and styling. They're the building blocks of Vue applications, allowing you to split your interface into independent, reusable pieces.
Slots
Files
Editor
Initializing WebContainer
Mounting files
Installing dependencies
Starting Nuxt server
Waiting for Nuxt to ready
Terminal