Emitting events
A child component often needs to tell its parent that something happened: a button was clicked, a value changed. The child cannot reach up and change the parent's data, so it sends a message instead.
Vue calls that message an event. You declare the events a component can emit
with defineEmits, then call the returned function to send one:
<script setup>
const emit = defineEmits(['increment']);
function onClick() {
emit('increment');
}
</script>
<template>
<button @click="onClick">Add</button>
</template>
defineEmits(['increment']) says this component may emit an event named
increment. Calling emit('increment') fires it, and a parent listens with
@increment="...", exactly like a native event. defineEmits is a compiler
macro, so you never import it.
The name you declare is the name the parent listens for; the two must match. The parent decides what to do with the event, so the child stays reusable and unaware of how its message is handled. The Test clicks the button and checks that the component emitted the event.
Challenge
The button does nothing. Make the component report the click: export an App
component from App.vue that declares an increment event and emits it when
the button is clicked.
The Test clicks the button and checks the component emitted increment. The
starter renders a button with no click handler, so nothing is emitted and the
Test fails. Add the handler that emits the event.