Custom events ($emit)
Children tell their parent that something happened by emitting a custom event.
In this page:
Syntax
// 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)
<!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
- Forgetting to declare emits
- Changing parent state directly from the child
- 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: