0
0
Vueframework~5 mins

Emitting custom events in Vue

Choose your learning style9 modes available
Introduction

Custom events let components talk to each other in Vue. They help a child component send messages to its parent.

When a child component needs to tell its parent that something happened, like a button click.
When you want to keep components separate but still let them share information.
When building reusable components that need to notify their users about changes.
When you want to handle user actions in a parent component but trigger them in a child.
When you want to keep your app organized by passing events up instead of changing data directly.
Syntax
Vue
<template>
  <button @click="$emit('eventName', eventData)">Click me</button>
</template>

<script setup>
// No extra code needed here
</script>

The $emit function sends an event from child to parent.

You can pass extra data as the second argument to $emit.

Examples
This emits an 'increment' event without extra data.
Vue
<template>
  <button @click="$emit('increment')">Add</button>
</template>
This emits an 'update' event and sends the number 5 as data.
Vue
<template>
  <button @click="$emit('update', 5)">Update to 5</button>
</template>
This emits 'input-changed' with the current input value whenever the user types.
Vue
<template>
  <input @input="$emit('input-changed', $event.target.value)" />
</template>
Sample Program

The child component emits a 'greet' event with a name. The parent listens and updates the message.

Vue
<template>
  <ChildComponent @greet="handleGreet" />
  <p>{{ message }}</p>
</template>

<script setup>
import { ref } from 'vue'
import ChildComponent from './ChildComponent.vue'

const message = ref('')

function handleGreet(name) {
  message.value = `Hello, ${name}!` 
}
</script>

<!-- ChildComponent.vue -->
<template>
  <button @click="$emit('greet', 'Vue Learner')">Say Hello</button>
</template>

<script setup>
// No extra code needed
</script>
OutputSuccess
Important Notes

Always listen for custom events in the parent using @eventName.

Use descriptive event names to keep your code clear.

Passing data with events helps parents know more about what happened.

Summary

Custom events let child components send messages to parents.

Use $emit('eventName', data) to send events.

Parents listen with @eventName="handler" to react.