← Back to Vue.js Course | Chapter 4: Components | Lesson 3 of 7

Custom events ($emit)

Children tell their parent that something happened by emitting a custom event.

In this page:

  1. Custom events ($emit)
Syntax
markup
// child
this.$emit('event-name', payload);

// parent template
<child-name @event-name="handler"></child-name>

Custom events ($emit)

A child calls this.$emit("event-name", payload), and the parent listens with @event-name. Declare emitted events in the emits option for clarity and validation. This keeps data flowing down through props and events flowing up.

Note: Name events in kebab-case when listening in templates.

Example: Custom events ($emit)

markup
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
  <p>Parent total: {{ total }}</p>
  <add-button :amount="5" @added="total += $event"></add-button>
</div>
<script>
  const app = Vue.createApp({ data() { return { total: 0 }; } });
  app.component("add-button", {
    props: ["amount"],
    emits: ["added"],
    template: '<button @click="$emit(\'added\', amount)">Add {{ amount }}</button>',
  });
  app.mount("#app");
  const b = document.querySelector("button");
  b.click(); b.click();
  Vue.nextTick(() => console.log(document.querySelector("p").textContent));
</script>
</body>
</html>

<!-- Output:
Rendered: Parent total: 10Add 5
console: Parent total: 10
-->
Live Example
Related Topics
Common Mistakes
  1. Forgetting to declare emits
  2. Changing parent state directly from the child
  3. Naming mismatches between emit and listener
Chapter Summary
  • $emit sends an event upward
  • The parent listens with @
  • Declare events in emits
  • Payload is passed as arguments
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.