What is defineEmits in Vue: Simple Explanation and Example
defineEmits in Vue is a function used inside the <script setup> block to declare events a component can emit. It helps Vue know which events the component sends out, making event handling clear and type-safe.How It Works
Imagine a component as a little machine that can send messages to its parent. defineEmits is like writing down the list of messages this machine can send. This helps everyone understand what to expect from it.
In Vue, components communicate by emitting events. Using defineEmits inside the <script setup> block tells Vue which events your component might send. This makes your code easier to read and helps catch mistakes early, like sending an event that wasn’t declared.
Example
This example shows a button component that emits a clicked event when pressed.
<template> <button @click="emit('clicked')">Click me</button> </template> <script setup> const emit = defineEmits(['clicked']) </script>
When to Use
Use defineEmits whenever your Vue component needs to send messages (events) to its parent. This is common in interactive components like buttons, forms, or custom inputs.
It helps keep your code organized and clear, especially in larger projects where many components communicate. For example, a form component might emit a submit event when the user sends data, or a modal might emit a close event when it should disappear.
Key Points
- defineEmits declares events a component can emit.
- It is used inside the
<script setup>block in Vue 3. - Helps with code clarity and error checking.
- Works like a contract between the component and its parent.
Key Takeaways
defineEmits declares which events a Vue component can send to its parent.<script setup> block for clear and safe event handling.