Emitting Events from Components
Sveip for å vise menyen
Components can send data back to their parent by emitting events. This allows child components to communicate when something happens, such as a button click.
To emit an event, use defineEmits() inside the component.
<!-- ButtonComponent.vue -->
<script setup>
const emit = defineEmits(["clickEvent"]);
function handleClick() {
emit("clickEvent");
}
</script>
<template>
<button @click="handleClick">Click</button>
</template>
The component emits a custom event called "clickEvent".
In the parent component, you listen to this event.
<script setup>
import ButtonComponent from "./components/ButtonComponent.vue";
function handleEvent() {
console.log("Event received");
}
</script>
<template>
<ButtonComponent @clickEvent="handleEvent" />
</template>
When the button is clicked, the event is emitted and handled in the parent.
Emitting events allows components to communicate and keep logic organized.
Alt var klart?
Takk for tilbakemeldingene dine!
Seksjon 1. Kapittel 12
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår
Seksjon 1. Kapittel 12