Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 87 ยท Components

Events and emits

Learn how Vue 3 components talk upward with custom events - emit with payloads, declare emits, validate them, listen with v-on on components, and follow naming conventions.

Props carry data down from a parent to a child. The reverse direction, from child to parent, uses events. A child does not reach into its parent and change things. It announces that something happened ("the user picked a rating", "the form was submitted") and the parent decides what to do about it. This keeps the child reusable: it only needs to know what happened, never who is listening.

In Vue the child calls emit("event-name", ...payload), and the parent listens with the same v-on (@) syntax you already use for DOM events in handling events. This lesson covers declaring events, passing payloads, validating them, and the naming conventions that keep a component's public API clear.

sequenceDiagram
  participant U as User
  participant C as Child component
  participant P as Parent component
  U->>C: clicks "Add"
  C->>P: emit("add", text)
  P->>P: handler updates the parent's state
  P->>C: new props flow down

An event travels up exactly one level: the child emits, the parent handles and updates its state, and new props flow back down.

Emitting an event

A child emits with the emit function. In the template it is available as $emit; in setup you receive it from the context (second argument); in an SFC with <script setup> you create it with the defineEmits macro (read-only here):

VUE
<script setup>
const emit = defineEmits(["rate"])

function pick(stars) {
  emit("rate", stars)
}
</script>

<template>
  <button @click="pick(5)">Five stars</button>
</template>

In the runnable object form, the equivalent is the emits option plus the emit from setup:

JavaScript
const StarPicker = {
  emits: ["rate"],
  setup(props, { emit }) {
    const pick = (stars) => emit("rate", stars);
    return { pick };
  },
  template: `...`,
};

The first argument of emit is the event name. Everything after it is the payload and arrives as arguments of the parent's handler. The parent listens with @rate="handler".

A child emits, the parent updates its state

Click a number, then Clear. The child never stores the rating itself: it receives current as a prop and reports clicks as events, which is the "props down, events up" cycle from the diagram. The rate event carries two payload values (stars and "picker"), and the parent's onRate(stars, source) receives both. For short handlers you can write an inline expression, as @clear="rating = 0" does; inside an inline expression the first payload value is available as $event.

Declaring emits

Always declare the events a component emits. It does three things:

  1. It documents the component's public API: someone reading the file sees what it can say.
  2. It lets Vue tell apart component events from native DOM listeners. A listener for an event that is not declared is also attached to the component's root element as a native listener (it "falls through", see fallthrough attributes). For an event whose name matches a native one, like click, that gives surprising double behavior.
  3. In development builds, it enables checks and better warnings.

The array form lists names. The object form lets you validate the payload: each key is an event name and the value is either null (no validation) or a function that returns true when the arguments are acceptable.

JavaScript
emits: {
  // no validation
  close: null,
  // validate the payload
  submit: ({ email }) => {
    if (email) return true;
    console.warn("submit needs an email");
    return false;
  },
}
VUE
<script setup>
const emit = defineEmits({
  close: null,
  submit: ({ email }) => Boolean(email),
})
</script>

An emit validator is a development aid, like a prop validator. When it returns false, a development build prints a warning, but the event is still emitted: the validator cannot cancel it. The checks only run in development builds, and the examples on this site load the production build, so you will not see warnings here. Use validators to catch programmer mistakes, and put real checks (for example "do not emit an empty text") in the code that decides whether to emit.

A child that validates before emitting

Press Add with an empty box: the child shows its hint and emits nothing. Add two tasks: both appear, but "First task added!" shows only once, because the second listener uses the .once modifier (the same modifier works on component events as on DOM events). The parent attached two handlers to the same event; both are called, in the order written.

The child keeps its own text and hint, because they are its private business, and publishes only the clean result. That is what makes NewTask reusable: the parent could use the same event to add to a list, to call a server, or to log.

Listening on components

On a component, @name listens for the component's own events. A few rules:

  • @add="addTask" calls addTask with the payload as arguments. @add="addTask($event)" and @add="(text) => addTask(text)" also work.
  • .once is supported. Modifiers that deal with DOM events (.prevent, .stop, .self, key modifiers) do not apply to component events, because there is no DOM event to cancel.
  • Emitted events do not bubble. If a grandchild emits save, only its direct parent hears it. To get the event further up, the middle component can listen and emit again, or you can share state instead (see provide and inject).
  • emit has no return value, and the child cannot get an answer back. If it needs one, pass a callback function as a prop, or have the parent change props in response.
Native click versus a declared click event

PlainButton declares no events, so the parent's @click becomes a native listener on the button and receives the DOM MouseEvent object. StrictButton declares click, so the parent's listener now receives whatever the child emits, here a string. Declaring events turns them into a deliberate API instead of an accident of the markup, which is why you should declare every event, even ones named like native events.

Events between unrelated components: the event bus

Component events only travel from a child to its direct parent. In Vue 2 people got around that with an event bus: an empty Vue instance used as a shared message channel (bus.$emit(...) in one component, bus.$on(...) in another). Vue 3 removed $on, $off and $once from instances, so that exact trick no longer works. The pattern itself is still possible with a tiny emitter object (libraries such as mitt are about 200 bytes), and it is fine for a few app-wide notifications like "show a toast".

A minimal event bus

The sender and receiver share nothing except the bus. Untick the box, send a few greetings, and tick it again: the new receiver starts from "nothing yet", because a bus has no memory. The onUnmounted call matters: without off, every removed component would stay subscribed and leak memory.

Use a bus sparingly. Events that nobody declares are hard to trace, and the sender cannot know who listens. For state that several components read, a shared reactive object or Pinia store is clearer (State sharing, Pinia); for a parent and a distant descendant, use provide and inject.

Naming conventions

  • Emit in camelCase or kebab-case, listen in kebab-case. emit("updateCount") is heard with @update-count; the kebab-case form in the template is the convention, and Vue also accepts the camelCase one in string templates and SFCs.
  • Name events after what happened, not what the parent should do: submit, close, item-selected, rather than delete-the-row. The child should not assume what the parent will do.
  • Use the update:propName form for two-way sync (update:modelValue). Vue treats it specially; v-model on components builds on it.
  • Keep the payload small and plain: a value, or one object. Many positional arguments are easy to mix up.
  • Do not emit events for things only the child cares about; keep private state private.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A child needs to tell its parent that the user clicked Save. What is the Vue way?

    Data flows down in props and notifications flow up as events. The child emits and the parent decides what to do.
  2. 2. A grandchild emits 'save'. Who receives it?

    Component events do not bubble. The middle component must handle it and emit again, or you can share the state in another way.
  3. 3. What happens when an emits validator returns false?

    The validator is a development aid. It can warn about a bad payload but it cannot stop the event from being emitted.
  4. 4. Why declare 'click' in emits when your component emits a custom click event?

    Undeclared listeners fall through to the root element as native DOM listeners. Declaring the event makes it a component event only.
  5. 5. How is an event emitted as emit('updateCount') normally listened to in a template?

    The convention is kebab-case in listeners, and Vue maps it to the camelCase event name.

Summary

  • Props go down, events go up: a child calls emit(name, ...payload) and the parent listens with @name.
  • Declare every event in emits (or defineEmits); it documents the API and stops undeclared listeners from falling through as native listeners.
  • Use the object form of emits for payload validators, but remember they are development warnings only and cannot cancel an event.
  • Component events do not bubble and return nothing; .once works, DOM modifiers like .prevent do not.
  • Name events for what happened, listen in kebab-case, and use update:propName for two-way sync.

Next: v-model on Components