Custom Events & Communication ($emit)
Custom events allow child components to communicate back up to their parents by emitting events, passing data payloads along with the notifications.
1 defineEmits custom triggers
Component communication in Vue follows a "Props Down, Events Up" pattern:
- defineEmits(): Macro used in the Composition API to declare custom events that the component can emit.
- emit() function: Emits an event with a specific name and optional payload data to parent listeners.
2 Custom Event Emitter Setup
Let's check how a child component emits events to its parent:
Vue — Child Component (Emitter)
<template>
<div class="item-card">
<h4>{{ title }}</h4>
<button @click="triggerSelect">Select</button>
</div>
</template>
<script setup>
const props = defineProps({
title: String
});
// Declare custom events
const emit = defineEmits(['selectedItem']);
function triggerSelect() {
// Emit event upwards, passing title as payload
emit('selectedItem', props.title);
}
</script>
The parent component listens to these events in its template:
HTML — Parent Event Listener
<app-item-card
title="Premium Laptop"
@selectedItem="handleSelectItem($event)">
</app-item-card>
3 Code Challenge
Challenge: Write a child component
QuantitySelector containing increment and decrement buttons that emits a changeQty event with values of +1 or -1 back to a parent count variable.