Component Events
A component event lets a child send a message up to its parent. The child emits the event, and the parent listens for it.
Declaring the event
In a script setup child, defineEmits names the event.
const emit = defineEmits(['chosen'])Emitting the event
The button emits chosen with the value Mint.
<button @click="$emit('chosen', 'Mint')">Mint</button>Listening in the parent
The parent runs pick when chosen arrives.
<Picker @chosen="pick" />Example
<script setup>
import { defineComponent, ref } from 'vue'
const picked = ref('None')
function pick(flavor) {
picked.value = flavor
}
const Picker = defineComponent({
emits: ['chosen'],
template: `<button @click="$emit('chosen', 'Mint')">Mint</button>`
})
</script>
<template>
<div>
<Picker @chosen="pick" />
<p>Picked: {{ picked }}</p>
</div>
</template>
Key points
- The child declares each event it can emit.
- The child emits the event with a value, like a choice.
- The parent listens with @ and the event name.
- The parent runs a function when the event arrives.
- Events flow one way, from child up to parent.
In this example, picked starts as the string None. Picker is a child with one button. The button emits the chosen event with Mint. The parent listens with @chosen and runs pick. pick stores Mint in picked, and the paragraph shows it.
Note
Props go down to the child, and events come back up.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
How does a child send a message to its parent?