We use cookies to enhance your experience on the site
CodeWorlds

Watch - Monitoring System

Sometimes you need to react to changes, not just calculate - like an alarm system monitoring mission parameters.

Basic watch()

1<template>
2  <div class="module-search" style="background: #0a0e27; color: #00ff88;">
3    <input v-model="searchQuery" placeholder="Search module..." style="background: #1a1e37; color: #00ff88;" />
4    <p v-if="isSearching" style="color: #00b4d8;">Searching...</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 on a single value
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  // Simulating API call to the NOVA LAB database
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>

Watch Options

1import { ref, watch } from 'vue'
2
3const count = ref(0)
4
5watch(count, (newValue) => {
6  console.log('Count:', newValue)
7}, {
8  immediate: true,  // Call immediately on initialization
9  deep: true,       // Deep observation of objects
10  flush: 'post',    // When to execute: 'pre', 'post', 'sync'
11  once: true        // Only once (Vue 3.4+)
12})

Watch on Multiple Sources

1import { ref, watch } from 'vue'
2
3const oxygenLevel = ref(95)
4const temperature = ref(22)
5
6// Array of sources - monitoring multiple parameters
7watch([oxygenLevel, temperature], ([newO2, newTemp], [oldO2, oldTemp]) => {
8  console.log(`Life support changed:
9    O2: ${oldO2}% → ${newO2}%
10    Temp: ${oldTemp}°C → ${newTemp}°C`)
11})

Watch on Getter

1import { reactive, watch } from 'vue'
2
3const reactor = reactive({
4  name: 'Plasma Core Alpha',
5  temperature: 2500
6})
7
8// Watch on getter (function)
9watch(
10  () => reactor.temperature,
11  (newTemp) => {
12    console.log('New reactor temperature:', newTemp)
13    if (newTemp > 5000) {
14      console.warn('CRITICAL: Temperature exceeds safe limits!')
15    }
16  }
17)
18
19// Watch on deep object
20watch(
21  () => reactor,
22  (newReactor) => {
23    console.log('Reactor config changed:', newReactor)
24  },
25  { deep: true }
26)
Go to CodeWorlds