Component events and emits

Beginner · 17 min

How a child talks back to its parent with custom events: declaring them with defineEmits, typed and validated payloads, and why they don't bubble.

Before thisComponents and propsEvent handling and modifiers

Laracasts · 17 min

Component events and emits

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by LaracastsReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Props carry data down; events carry messages up. A child never changes its parent's state directly. It emits an event, and the parent decides what to do.
  • In `<script setup>`, `defineEmits` declares the events a component can fire and returns an `emit` function: `emit('remove', id)` sends the event with any number of payload arguments.
  • The parent listens with `v-on` / `@`, exactly like a DOM event: `@remove="handleRemove"`. Emit in camelCase, listen in kebab-case; Vue converts between them.
  • Declaring events documents the component's interface, enables type-checking and payload validation, and keeps listeners for those events out of the fallthrough `$attrs`.
  • Component events do not bubble. Only the direct parent can listen, so reaching a distant ancestor needs provide/inject or a store, not a chain of re-emits.

The other half of one-way data flow

The props lesson ended on a rule: a child must not change its props. That raises an obvious question. A TodoItem has a delete button. The list of todos lives in the parent. How does clicking the button remove the item?

The answer is that the child doesn’t remove anything. It announces that the delete button was clicked, and the parent, which owns the list, decides what that means. Think of it like a restaurant: the diner doesn’t walk into the kitchen and cook, they tell the waiter what they want. Props are the food coming out; events are the orders going in.

Vue gives components their own event channel for this. A child emits a named event; the parent listens with the same @ syntax used for DOM events.

Declaring and emitting with defineEmits

In <script setup>, the defineEmits macro declares which events the component can fire and returns a function to fire them:

<!-- TodoItem.vue -->
<script setup>
const props = defineProps({
  todo: { type: Object, required: true },
})

const emit = defineEmits(['remove', 'toggle'])

function onDelete() {
  emit('remove', props.todo.id)
}
</script>

<template>
  <li>
    <input type="checkbox" :checked="todo.done" @change="emit('toggle', todo.id)" />
    {{ todo.text }}
    <button @click="onDelete">Delete</button>
  </li>
</template>

emit(name, ...args) fires the event. Everything after the name is payload, handed to the parent’s listener as arguments. Like defineProps, defineEmits is a compiler macro, so it only works at the top level of <script setup> and needs no import.

Inside a template you can also call $emit('remove', todo.id) directly. That’s convenient for one-liners, but $emit isn’t available in the script block, so the emit function from defineEmits is the one to use for anything with logic.

Listening in the parent

The parent listens exactly as it would for a click:

<script setup>
import { ref } from 'vue'
import TodoItem from './TodoItem.vue'

const todos = ref([
  { id: 1, text: 'Learn props', done: true },
  { id: 2, text: 'Learn emits', done: false },
])

function removeTodo(id) {
  todos.value = todos.value.filter((t) => t.id !== id)
}

function toggleTodo(id) {
  const todo = todos.value.find((t) => t.id === id)
  todo.done = !todo.done
}
</script>

<template>
  <ul>
    <TodoItem
      v-for="todo in todos"
      :key="todo.id"
      :todo="todo"
      @remove="removeTodo"
      @toggle="toggleTodo"
    />
  </ul>
</template>

The state change happens in the component that owns the state. The child stays reusable: it doesn’t know or care whether the list lives in a ref, a Pinia store, or on a server.

In an inline handler, the first payload argument is available as $event: @remove="lastRemoved = $event". Event names follow the same casing rule as props. Emit in camelCase (emit('itemSelected')) and listen in kebab-case (@item-selected); Vue maps one to the other. The .once modifier also works on component events.

Typed and validated events

With TypeScript, defineEmits can take a type that lists each event and its payload as a named tuple (Vue 3.3+):

<script setup lang="ts">
const emit = defineEmits<{
  remove: [id: number]
  rename: [id: number, text: string]
}>()

emit('remove', 42)        // ok
emit('rename', 42)        // type error: missing text
</script>

The editor now catches a misspelled event name or a missing argument. The details of typing emits belong to the TypeScript with Vue lesson.

Without TypeScript, the object syntax adds a runtime check. Each key is an event name; the value is null for no validation or a function that receives the payload and returns whether it is valid:

const emit = defineEmits({
  remove: (id) => typeof id === 'number',
  toggle: null,
})

An invalid payload produces a console warning in development. The event is still emitted.

Why declare events at all

A component can call $emit for an undeclared event and it will still work. Declaring them is still worth it:

  • The emits list is documentation. Anyone opening the file sees the component’s full interface, inputs and outputs, at the top.
  • Types and validators only apply to declared events.
  • Declared event listeners are removed from the component’s fallthrough attributes. An undeclared @remove listener lands in $attrs and gets attached to the root element as a native listener, which is covered in fallthrough attributes.

That last point has a sharp edge. If you declare a native event name such as click in emits, the parent’s @click now listens only for your component’s emitted click. A native click on the root element no longer triggers it unless you emit it yourself.

Events don’t bubble

Native DOM events bubble up through ancestors, as covered in DOM events. Component events do not. Only the direct parent can listen. If a grandchild emits saved, a listener on the grandparent never fires.

You could re-emit at every level, but that is the event version of prop drilling and it gets brittle quickly. When a distant ancestor needs to know, share state with provide and inject or a store such as Pinia instead.

React handles the same problem differently. A parent passes a callback such as onRemove as a prop, and the child calls it, as covered in handling events in React. Vue can do that too, since a function is a valid prop, but emits keep “data in” and “messages out” visibly separate.

What the video covers

Jeffrey Way’s Laracasts episode takes a reusable “tabbable” textarea from the series and refactors it to <script setup>, replacing its old declarations with defineEmits and defineProps along the way. It is a good look at how the macros work in a real component and why they need no import. It is the 21st episode of a series, so the running example is assumed context, and it uses the runtime array/object declaration rather than the 3.3 typed tuple syntax shown above. Leela Web Dev’s video goes deeper on payload validation with the object syntax. Syntax’s crash course shows emits in a current TypeScript project, including the “emit instead of mutating a prop” pattern.

Check yourself

  1. 01A `TodoItem` shows a delete button. Why should it emit an event instead of removing itself from the parent's `todos` array?

    The array belongs to the parent, and props flow one way, so the child has no business mutating it. Emitting `remove` with the item's id tells the parent what happened and leaves the decision to the owner of the data: the parent can filter the array, ask for confirmation, or ignore it. The child stays reusable because it doesn't assume anything about where the list lives.

  2. 02The child calls `emit('itemSelected', item)`. How should the parent's template listen for it, and how does it receive `item`?

    Use the kebab-case listener `@item-selected="onSelect"`; Vue maps it to the camelCase event name. Extra arguments passed to `emit` become the handler's arguments, so `onSelect(item)` receives it. In an inline handler, the first payload argument is available as `$event`.

  3. 03A grandchild component emits `saved`. The grandparent has `@saved` on the middle component, but the handler never runs. Why?

    Component events do not bubble the way native DOM events do. Only the component's direct parent can listen for them. The middle component would have to listen and re-emit, or the components should share state through provide/inject or a store instead.

  4. 04What changes when a component declares `click` in its `emits` list?

    Vue treats the parent's `@click` listener as a listener for the component's own emitted `click` event only. It no longer falls through to the root element as a native listener, so a native click on the root element won't trigger it; the component must call `emit('click')` itself.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark