Czasem potrzebujesz reagować na zmiany, nie tylko obliczać - jak system alarmowy monitorujący parametry misji.
1<template>
2 <div class="module-search" style="background: #0a0e27; color: #00ff88;">
3 <input v-model="searchQuery" placeholder="Szukaj modułu..." style="background: #1a1e37; color: #00ff88;" />
4 <p v-if="isSearching" style="color: #00b4d8;">Wyszukiwanie...</p>
5 <ul>
6 <li v-for="result in searchResults" :key="result.id" style="border-bottom: 1px solid #00b4d8;">
7 {{ result.name }}
8 </li>
9 </ul>
10 </div>
11</template>
12
13<script setup>
14import { ref, watch } from 'vue'
15
16const searchQuery = ref('')
17const searchResults = ref([])
18const isSearching = ref(false)
19
20// Watch na pojedynczą wartość
21watch(searchQuery, async (newQuery, oldQuery) => {
22 console.log(`Search changed: "${oldQuery}" → "${newQuery}"`)
23
24 if (newQuery.length < 2) {
25 searchResults.value = []
26 return
27 }
28
29 isSearching.value = true
30
31 // Symulacja API call do bazy NOVA LAB
32 await new Promise(resolve => setTimeout(resolve, 500))
33
34 searchResults.value = [
35 { id: 1, name: `Module: ${newQuery}` }
36 ]
37
38 isSearching.value = false
39})
40</script>1import { ref, watch } from 'vue'
2
3const count = ref(0)
4
5watch(count, (newValue) => {
6 console.log('Count:', newValue)
7}, {
8 immediate: true, // Wywołaj natychmiast przy inicjalizacji
9 deep: true, // Głębokie obserwowanie obiektów
10 flush: 'post', // Kiedy wykonać: 'pre', 'post', 'sync'
11 once: true // Tylko raz (Vue 3.4+)
12})1import { ref, watch } from 'vue'
2
3const oxygenLevel = ref(95)
4const temperature = ref(22)
5
6// Tablica źródeł - monitorowanie wielu parametrów
7watch([oxygenLevel, temperature], ([newO2, newTemp], [oldO2, oldTemp]) => {
8 console.log(`Life support changed:
9 O2: ${oldO2}% → ${newO2}%
10 Temp: ${oldTemp}°C → ${newTemp}°C`)
11})1import { reactive, watch } from 'vue'
2
3const reactor = reactive({
4 name: 'Plasma Core Alpha',
5 temperature: 2500
6})
7
8// Watch na getter (funkcję)
9watch(
10 () => reactor.temperature,
11 (newTemp) => {
12 console.log('Nowa temperatura reaktora:', newTemp)
13 if (newTemp > 5000) {
14 console.warn('CRITICAL: Temperature exceeds safe limits!')
15 }
16 }
17)
18
19// Watch na głęboki obiekt
20watch(
21 () => reactor,
22 (newReactor) => {
23 console.log('Reactor config changed:', newReactor)
24 },
25 { deep: true }
26)