Episode 24 of 44

Events (child to parent)

Emit custom events from child components to communicate with parents — the Vue pattern for upward data flow.

Events (child to parent)

Props send data down. Custom events send messages up. When a child component needs to tell its parent something — like "the user clicked delete" or "the title changed" — it emits a custom event.

Emitting an Event

<!-- Child: NinjaCard.vue -->
<template>
    <div class="card">
        <h3>{{ ninja.name }}</h3>
        <button @click="deleteNinja">Delete</button>
    </div>
</template>

<script>
export default {
    props: ['ninja'],
    methods: {
        deleteNinja() {
            this.$emit('delete-ninja', this.ninja.name);
        }
    }
};
</script>

this.$emit('event-name', data) fires a custom event. The first argument is the event name; the second (optional) is data to send with the event.

Listening in the Parent

<!-- Parent: Ninjas.vue -->
<template>
    <div>
        <NinjaCard
            v-for="ninja in ninjas"
            :key="ninja.name"
            :ninja="ninja"
            @delete-ninja="removeNinja"
        />
    </div>
</template>

<script>
export default {
    methods: {
        removeNinja(name) {
            this.ninjas = this.ninjas.filter(n => n.name !== name);
        }
    }
};
</script>

@delete-ninja="removeNinja" listens for the delete-ninja event and calls removeNinja with the emitted data.

The Data Flow Pattern

Parent (data owner)
  │
  │── :ninja="ninja" ──→  Child (displays data)
  │                           │
  │←── @delete-ninja ────────│  $emit('delete-ninja', name)
  │
  │ Modifies its own data

Key Takeaways

  • this.$emit('event-name', data) sends a custom event from child to parent
  • The parent listens with @event-name="handler"
  • Data flows down via props; events flow up via $emit
  • Only the data owner should modify the data — children request changes via events