Vue.js course Β· Module 4: Computed & Watch

Watch - Monitoring System

6 min read Β·
In this lesson4

A computed answers the question "how much is it", but a good part of the station's work is not about values, it is about reactions. When an operator types a module name, the NOVA LAB database has to be queried. When the reactor temperature exceeds the norm, an alarm has to go off and the event has to be written to the log. Side effects like these must never go into a computed, because its getter should only calculate and return a result right away. Reacting to changes is the job of a watcher, the alarm sensor of Mission Control.

Basic watch()

The watch function takes two arguments and an optional third one. The first is the source, the thing we observe: a ref, an object from reactive, a getter, or an array of such sources. The second is the callback, which Vue calls after every change of the source, passing it the new and the previous value. A watcher is lazy by default: when created it does nothing and waits for the first change. Below is a module search in which the callback is an async function, and the database response delay is faked with await on a promise resolved by setTimeout.

<template>
  <div class="module-search" style="background: #0a0e27; color: #00ff88;">
    <input v-model="searchQuery" placeholder="Search module..." style="background: #1a1e37; color: #00ff88;" />
    <p v-if="isSearching" style="color: #00b4d8;">Searching...</p>
    <ul>
      <li v-for="result in searchResults" :key="result.id" style="border-bottom: 1px solid #00b4d8;">
        {{ result.name }}
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'

const searchQuery = ref('')
const searchResults = ref([])
const isSearching = ref(false)

// Watch on a single value
watch(searchQuery, async (newQuery, oldQuery) => {
  console.log(`Search changed: "${oldQuery}" β†’ "${newQuery}"`)

  if (newQuery.length < 2) {
    searchResults.value = []
    return
  }

  isSearching.value = true

  // Simulating API call to the NOVA LAB database
  await new Promise(resolve => setTimeout(resolve, 500))

  searchResults.value = [
    { id: 1, name: `Module: ${newQuery}` }
  ]

  isSearching.value = false
})
</script>

Type "ox", and a line with the old and new query appears in the console, followed half a second later by the search result. Queries shorter than two characters clear the list and end the callback with a return statement before anything is sent. What did not change: searchQuery is still an ordinary ref bound with v-model, and the watcher writes nothing into it, it only listens. Also notice the moment of the reaction. Vue does not call the callback on the same line where you change the value: it picks up the change and handles it in the next tick, before the DOM is refreshed. Two changes within one tick therefore produce a single call, already carrying the latest value.

Watch Options

The third argument is an options object. immediate: true runs the callback right away when the watcher is created, with the old value equal to undefined, which comes in handy for loading data when a panel starts. deep: true turns on deep observation of nested objects. flush picks the moment of the call: 'pre' (the default, before the DOM update), 'post' (after the update, when you want to read the refreshed DOM) or 'sync' (immediately on every change). once: true, available since Vue 3.4, stops the watcher after its first call.

import { ref, watch } from 'vue'

const count = ref(0)

watch(count, (newValue) => {
  console.log('Count:', newValue)
}, {
  immediate: true,  // Call immediately on initialization
  deep: true,       // Deep observation of objects
  flush: 'post',    // When to execute: 'pre', 'post', 'sync'
  once: true        // Only once (Vue 3.4+)
})

This block is a cheat sheet, not a pattern to copy. count is a number, so deep changes nothing here, and combining immediate with once means the callback runs once, right at creation, and the watcher switches itself off immediately. In practice the configuration always goes in the same order: import watch from vue, the source, the callback, and at the end only the options you really need.

Watch on Multiple Sources

Life support systems are assessed together: oxygen and temperature. Instead of two watchers you pass an array of sources. The callback then receives an array of new values and an array of old ones, in the same order as the sources, and the destructuring [newO2, newTemp] names them on the spot.

import { ref, watch } from 'vue'

const oxygenLevel = ref(95)
const temperature = ref(22)

// Array of sources - monitoring multiple parameters
watch([oxygenLevel, temperature], ([newO2, newTemp], [oldO2, oldTemp]) => {
  console.log(`Life support changed:
    O2: ${oldO2}% β†’ ${newO2}%
    Temp: ${oldTemp}Β°C β†’ ${newTemp}Β°C`)
})

The callback runs when any of the sources changes. If only the oxygen changed, newTemp and oldTemp are equal. The watcher does not tell you which source moved, so compare the pairs yourself when you need to know.

Watch on Getter

An object from reactive calls for care. Writing watch(reactor.temperature, callback) will not work, because that way you pass the number 2500 rather than a reactive source, and Vue warns about an invalid watch source. You observe an object property through a getter, the function () => reactor.temperature, which Vue calls to read the current value.

import { reactive, watch } from 'vue'

const reactor = reactive({
  name: 'Plasma Core Alpha',
  temperature: 2500
})

// Watch on getter (function)
watch(
  () => reactor.temperature,
  (newTemp) => {
    console.log('New reactor temperature:', newTemp)
    if (newTemp > 5000) {
      console.warn('CRITICAL: Temperature exceeds safe limits!')
    }
  }
)

// Watch on deep object
watch(
  () => reactor,
  (newReactor) => {
    console.log('Reactor config changed:', newReactor)
  },
  { deep: true }
)

The first watcher reacts to the temperature only - renaming the reactor will not wake it up. The second observes a getter that returns the whole object, which is why it needs { deep: true }. Without that option it would not react to a change in any field, because a getter without deep wakes the watcher only when it returns a different value than before, and here it keeps returning the same object. A reactive object passed directly, without a getter, creates a deep watcher automatically. With a ref holding an object it is the other way round: a change to a nested field such as missionData.value.systems.oxygen goes unnoticed without deep: true. After such an in-place change, the new and the old value point to the same object, so comparing them tells you nothing.

Keep the cost in mind: on every run deep walks through all nested fields, which can get expensive on large structures. Since Vue 3.5 you can limit the depth with a number, for example deep: 2. Still, I recommend that you first reach for a getter that points at the specific field - a sensor wired to a single cable is cheaper than a scanner for the whole module. In the next lesson you will meet watchEffect, which finds its sources by itself.

Remember: watch is an alarm sensor - you point it at a source, and on every change it reports both the new and the previous reading.

Code for this lesson: App.vue
<script setup>
import { ref, watch } from 'vue'

// NOVA LAB - System Monitoring with watch()
const oxygenLevel = ref(95)
const powerLevel = ref(2800)
const waterLevel = ref(85)
const logs = ref([])

// watch() - reacts to specific source changes
watch(oxygenLevel, (newValue, oldValue) => {
  const timestamp = new Date().toLocaleTimeString()
  logs.value.unshift({
    time: timestamp,
    type: 'oxygen',
    message: `Oxygen: ${oldValue}% β†’ ${newValue}%`,
    color: newValue < 80 ? '#ff0044' : '#00ff88'
  })

  if (newValue < 80) {
    logs.value.unshift({
      time: timestamp,
      type: 'warning',
      message: 'WARNING: Low oxygen level detected!',
      color: '#ffaa00'
    })
  }
})

watch(powerLevel, (newValue, oldValue) => {
  const timestamp = new Date().toLocaleTimeString()
  logs.value.unshift({
    time: timestamp,
    type: 'power',
    message: `Power: ${oldValue}W β†’ ${newValue}W`,
    color: newValue < 2000 ? '#ff0044' : '#00b4d8'
  })

  if (newValue < 2000) {
    logs.value.unshift({
      time: timestamp,
      type: 'critical',
      message: 'CRITICAL: Power below minimum threshold!',
      color: '#ff0044'
    })
  }
})

// Watch multiple sources
watch([oxygenLevel, powerLevel, waterLevel], ([o2, power, water]) => {
  const allOptimal = o2 > 90 && power > 2500 && water > 80
  if (allOptimal) {
    const timestamp = new Date().toLocaleTimeString()
    logs.value.unshift({
      time: timestamp,
      type: 'success',
      message: 'All systems optimal!',
      color: '#00ff88'
    })
  }
})

function adjustOxygen(delta) {
  oxygenLevel.value = Math.max(0, Math.min(100, oxygenLevel.value + delta))
}

function adjustPower(delta) {
  powerLevel.value = Math.max(0, powerLevel.value + delta)
}

function adjustWater(delta) {
  waterLevel.value = Math.max(0, Math.min(100, waterLevel.value + delta))
}

function clearLogs() {
  logs.value = []
}

function simulateEmergency() {
  oxygenLevel.value = 65
  powerLevel.value = 1500
  waterLevel.value = 45
}

function restoreNominal() {
  oxygenLevel.value = 95
  powerLevel.value = 2800
  waterLevel.value = 85
}
</script>

<template>
  <div class="monitor-system">
    <div class="header">
      <h1>NOVA LAB System Monitor</h1>
      <p class="subtitle">watch() API - Reactive Monitoring</p>
    </div>

    <div class="controls-panel">
      <div class="system-control">
        <h3>Oxygen System</h3>
        <div class="level-bar">
          <div
            class="level-fill oxygen"
            :style="{ width: oxygenLevel + '%' }"
          ></div>
          <span class="level-text">{{ oxygenLevel }}%</span>
        </div>
        <div class="buttons">
          <button @click="adjustOxygen(-10)">-10%</button>
          <button @click="adjustOxygen(-5)">-5%</button>
          <button @click="adjustOxygen(5)">+5%</button>
          <button @click="adjustOxygen(10)">+10%</button>
        </div>
      </div>

      <div class="system-control">
        <h3>Power System</h3>
        <div class="level-bar">
          <div
            class="level-fill power"
            :style="{ width: (powerLevel / 30) + '%' }"
          ></div>
          <span class="level-text">{{ powerLevel }}W</span>
        </div>
        <div class="buttons">
          <button @click="adjustPower(-200)">-200W</button>
          <button @click="adjustPower(-100)">-100W</button>
          <button @click="adjustPower(100)">+100W</button>
          <button @click="adjustPower(200)">+200W</button>
        </div>
      </div>

      <div class="system-control">
        <h3>Water Reserves</h3>
        <div class="level-bar">
          <div
            class="level-fill water"
            :style="{ width: waterLevel + '%' }"
          ></div>
          <span class="level-text">{{ waterLevel }}%</span>
        </div>
        <div class="buttons">
          <button @click="adjustWater(-10)">-10%</button>
          <button @click="adjustWater(-5)">-5%</button>
          <button @click="adjustWater(5)">+5%</button>
          <button @click="adjustWater(10)">+10%</button>
        </div>
      </div>
    </div>

    <div class="scenario-buttons">
      <button @click="simulateEmergency" class="danger">Simulate Emergency</button>
      <button @click="restoreNominal" class="success">Restore Nominal</button>
      <button @click="clearLogs" class="neutral">Clear Logs</button>
    </div>

    <div class="log-panel">
      <h3>System Event Log</h3>
      <div class="log-entries">
        <div
          v-for="(log, index) in logs.slice(0, 15)"
          :key="index"
          class="log-entry"
          :style="{ borderLeftColor: log.color, color: log.color }"
        >
          <span class="log-time">[{{ log.time }}]</span>
          <span class="log-message">{{ log.message }}</span>
        </div>
        <div v-if="logs.length === 0" class="no-logs">
          No events logged yet. Adjust system parameters to see watch() in action!
        </div>
      </div>
    </div>

    <div class="info-box">
      <strong>watch() API:</strong> Monitors specific reactive sources and executes callbacks when they change.
      Perfect for logging, side effects, and conditional responses!
    </div>
  </div>
</template>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: 'Courier New', monospace;
  background: #0a0e27;
  color: #00ff88;
  padding: 20px;
}

.monitor-system {
  max-width: 1100px;
  margin: 0 auto;
}

.header {
  text-align: center;
  margin-bottom: 30px;
  padding: 20px;
  background: linear-gradient(135deg, #1a1f4c 0%, #0a0e27 100%);
  border: 2px solid #00ff88;
  border-radius: 10px;
}

.header h1 {
  font-size: 2rem;
  margin-bottom: 10px;
  text-shadow: 0 0 20px #00ff88;
}

.subtitle {
  color: #00b4d8;
  font-size: 1.1rem;
}

.controls-panel {
  display: grid;
  gap: 20px;
  margin-bottom: 20px;
}

.system-control {
  background: rgba(0, 180, 216, 0.05);
  border: 2px solid #00b4d8;
  border-radius: 10px;
  padding: 20px;
}

.system-control h3 {
  color: #00b4d8;
  margin-bottom: 15px;
}

.level-bar {
  position: relative;
  height: 40px;
  background: rgba(0, 0, 0, 0.5);
  border: 1px solid #00ff88;
  border-radius: 5px;
  margin-bottom: 15px;
  overflow: hidden;
}

.level-fill {
  height: 100%;
  transition: width 0.3s ease;
}

.level-fill.oxygen {
  background: linear-gradient(90deg, #00ff88, #00cc66);
}

.level-fill.power {
  background: linear-gradient(90deg, #00b4d8, #0088ff);
}

.level-fill.water {
  background: linear-gradient(90deg, #0088ff, #0066cc);
}

.level-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-weight: bold;
  font-size: 1.2rem;
  color: white;
  text-shadow: 0 0 5px black;
}

.buttons {
  display: flex;
  gap: 10px;
  justify-content: center;
}

button {
  background: linear-gradient(135deg, #00b4d8 0%, #0077aa 100%);
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  font-family: 'Courier New', monospace;
  font-weight: bold;
  transition: all 0.3s ease;
}

button:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0, 180, 216, 0.3);
}

.scenario-buttons {
  display: flex;
  gap: 15px;
  justify-content: center;
  margin-bottom: 20px;
}

.scenario-buttons button {
  padding: 15px 30px;
  font-size: 1rem;
}

.danger {
  background: linear-gradient(135deg, #ff0044 0%, #cc0033 100%) !important;
}

.success {
  background: linear-gradient(135deg, #00ff88 0%, #00cc66 100%) !important;
}

.neutral {
  background: linear-gradient(135deg, #666 0%, #444 100%) !important;
}

.log-panel {
  background: rgba(0, 0, 0, 0.5);
  border: 2px solid #00ff88;
  border-radius: 10px;
  padding: 20px;
  margin-bottom: 20px;
}

.log-panel h3 {
  color: #00ff88;
  margin-bottom: 15px;
}

.log-entries {
  max-height: 300px;
  overflow-y: auto;
}

.log-entry {
  padding: 10px;
  margin-bottom: 8px;
  background: rgba(0, 255, 136, 0.05);
  border-left: 4px solid;
  border-radius: 4px;
  font-size: 0.9rem;
  animation: slideIn 0.3s ease;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateX(-20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

.log-time {
  opacity: 0.7;
  margin-right: 10px;
}

.no-logs {
  text-align: center;
  padding: 30px;
  color: #666;
  font-style: italic;
}

.info-box {
  background: rgba(0, 255, 136, 0.1);
  border: 2px solid #00ff88;
  border-radius: 10px;
  padding: 15px;
  text-align: center;
  color: #00ff88;
  line-height: 1.6;
}
</style>

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What is the purpose of watch() in Vue.js?

  2. 2. What parameters does the callback in watch() receive?

These are 2 of 4 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Click in order

    Arrange the correct watch syntax:

  • Code editor

    Complete the watch that observes searchQuery and logs changes with the new and old values.

  • Vertical ordering

    Arrange the watch configuration steps in the correct order:

  • Code editor

    Complete the watch with the immediate: true option to fetch data immediately after the watcher is created.

  • Vertical ordering

    Arrange the watch operation stages from source change to callback:

  • Horizontal ordering

    Arrange watch with the deep option in the correct order:

  • Code editor

    Complete the watch with { deep: true } to observe changes in a nested reactive object.

  1. QuestionPurpose of the watch function
  2. QuestionWatch callback parameters
  3. Click in orderWatch syntax
  4. Coding taskPractice: Basic Watch
  5. QuestionThe immediate option in watch
  6. Put in orderWatch configuration step by step
  7. Coding taskPractice: Watch with Immediate
  8. QuestionThe deep option in watch
  9. Put in orderWatcher operation stages
  10. Put in orderWatch with options
  11. Coding taskPractice: Deep Watch on Object

Useful articles