0
0
Vueframework~5 mins

Events for child to parent communication in Vue

Choose your learning style9 modes available
Introduction

Sometimes a child component needs to tell its parent something. Events let the child send messages up to the parent easily.

When a button inside a child component is clicked and the parent needs to know.
When a form inside a child component is submitted and the parent should handle the data.
When a child component changes a value and the parent needs to update something.
When you want to keep child components reusable and let parents decide what to do with events.
Syntax
Vue
<ChildComponent @event-name="parentMethod" />

// Inside ChildComponent
this.$emit('event-name', payload)

The child uses $emit to send an event up.

The parent listens with @event-name on the child component tag.

Examples
Child sends a 'clicked' event. Parent runs handleClick when it happens.
Vue
<ChildButton @clicked="handleClick" />

// ChildButton.vue
this.$emit('clicked')
Child sends new value to parent using event with data.
Vue
<ChildInput @input-changed="updateValue" />

// ChildInput.vue
this.$emit('input-changed', newValue)
Sample Program

The child button sends an 'incremented' event when clicked. The parent listens and increases the count. The count shows updated on screen.

Vue
<template>
  <div>
    <ChildCounter @incremented="increaseCount" />
    <p>Count: {{ count }}</p>
  </div>
</template>

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

const count = ref(0)

function increaseCount() {
  count.value++
}
</script>

<!-- ChildCounter.vue -->
<template>
  <button @click="$emit('incremented')">Add 1</button>
</template>

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

Always name events clearly to know what they mean.

Events help keep child components simple and reusable.

Use $emit only inside child components.

Summary

Child components use $emit to send events to parents.

Parents listen with @event-name on child tags.

This pattern helps components talk without tight connections.