W Stacji Komunikacji sygnał nie idzie tylko w jedną stronę! Gdy Mars odbierze dane, wysyła potwierdzenie z powrotem na Ziemię. W Vue dziecko komunikuje się z rodzicem przez custom events - sygnały emitowane w górę drzewa komponentów.
W
<script setup> deklarujemy emitowane eventy przez defineEmits:1<!-- SignalButton.vue (dziecko) -->
2<script setup>
3const emit = defineEmits(['signal-sent', 'error'])
4
5const sendSignal = () => {
6 emit('signal-sent', { message: 'OK', time: Date.now() })
7}
8
9const reportError = (code) => {
10 emit('error', code)
11}
12</script>
13
14<template>
15 <button @click="sendSignal">Send</button>
16</template>Rodzic nasłuchuje eventów przez
@event-name lub v-on:event-name:1<!-- Parent.vue -->
2<template>
3 <SignalButton
4 @signal-sent="handleSignal"
5 @error="handleError"
6 />
7</template>
8
9<script setup>
10const handleSignal = (data) => {
11 console.log('Signal received:', data.message)
12}
13
14const handleError = (code) => {
15 console.error('Error:', code)
16}
17</script>Emit może przekazywać dowolne dane jako payload:
1<script setup>
2const emit = defineEmits(['submit'])
3
4const onSubmit = () => {
5 // Jeden argument
6 emit('submit', 'data')
7
8 // Wiele argumentów
9 emit('submit', name, email, role)
10
11 // Obiekt
12 emit('submit', { name, email, role })
13}
14</script>Obiektowa składnia
defineEmits pozwala walidować payload:1<script setup>
2const emit = defineEmits({
3 // Bez walidacji
4 click: null,
5
6 // Z walidacją
7 submit: (payload) => {
8 if (!payload.email) return false
9 if (!payload.email.includes('@')) return false
10 return true
11 }
12})
13</script>