How to Use emit in Vue: Simple Event Communication
In Vue, use
emit inside a child component to send custom events to its parent. The parent listens with @eventName on the child component tag to react when the event is emitted.Syntax
The emit function is called inside a child component to send an event to its parent. It takes the event name as the first argument and optional data as the second.
emit('eventName'): Sends an event without data.emit('eventName', payload): Sends an event with data.
The parent listens using @eventName="handlerMethod" on the child component tag.
vue
const emit = defineEmits(['customEvent']) // To emit without data emit('customEvent') // To emit with data emit('customEvent', payload)
Example
This example shows a child button component emitting a clicked event when pressed. The parent listens and updates a message.
vue
<!-- ChildButton.vue --> <template> <button @click="handleClick">Click me</button> </template> <script setup> const emit = defineEmits(['clicked']) function handleClick() { emit('clicked', 'Button was clicked!') } </script> <!-- ParentComponent.vue --> <template> <ChildButton @clicked="onChildClicked" /> <p>{{ message }}</p> </template> <script setup> import ChildButton from './ChildButton.vue' import { ref } from 'vue' const message = ref('Waiting for click...') function onChildClicked(payload) { message.value = payload } </script>
Output
A button labeled 'Click me' and below it text that changes from 'Waiting for click...' to 'Button was clicked!' when the button is clicked.
Common Pitfalls
Common mistakes when using emit include:
- Not defining the event name in
defineEmits(Vue 3 script setup) which can cause warnings. - Parent forgetting to listen with
@eventNameso the event has no effect. - Using the wrong event name or casing mismatch between emit and listener.
- Trying to emit events from the parent to child (emit only works child to parent).
vue
<!-- Wrong: emitting event not declared --> <script setup> const emit = defineEmits([]) emit('missingEvent') // Warning: event not declared </script> <!-- Right: declare event --> <script setup> const emit = defineEmits(['missingEvent']) emit('missingEvent') </script>
Quick Reference
| Action | Syntax | Description |
|---|---|---|
| Declare events | const emit = defineEmits(['eventName']) | Declare which events child can emit |
| Emit event without data | emit('eventName') | Send event to parent without payload |
| Emit event with data | emit('eventName', data) | Send event with payload to parent |
| Listen in parent | Parent reacts to child's event |
Key Takeaways
Use
emit in child components to send events to parents.Always declare emitted events with
defineEmits in script setup.Parents listen with
@eventName on child component tags.Event names must match exactly between emit and listener.
Emit only works child-to-parent, not the other way around.