Vue.js course · Module 4: Computed & Watch

Computed and Watch in Practice - Mission Systems

8 min read ·
In this lesson4

Mission Control has ordered three panels: a module search that does not bombard the server with a request after every letter, a trajectory calculator with a history of results, and a registration form with validation. Each one combines computed with a watcher, and the whole art lies in not mixing up the roles. The rule is short: when you need a value, write a computed, and when you need an action - a request, a log entry, a timer - write a watch. The computed getter must stay pure: it only calculates and returns a result, it does not send requests, does not write to localStorage and does not change other data.

Module Search System with Debounce

An operator typing the word "reactor" would send seven requests, although only the last one matters. The debounce technique holds the action back until the data stops changing for a set time, here 300 milliseconds. Let us start with the template: a search field, a loading message and a list of results.

<template>
  <div class="module-search-system" style="background: #0a0e27; color: #00ff88;">
    <input v-model="searchInput" placeholder="Search modules..." style="background: #1a1e37; color: #00ff88;" />
    <p v-if="isLoading" style="color: #00b4d8;">Scanning NOVA LAB database...</p>
    <ul>
      <li v-for="item in results" :key="item.id" style="border-bottom: 1px solid #00b4d8;">
        {{ item.name }}
      </li>
    </ul>
  </div>
</template>

The field is bound to searchInput, the raw text that changes after every keystroke. The list reads results, and the message shows up while isLoading is true. Now the script with the first watcher, which delays copying the text into searchQuery.

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

const searchInput = ref('')
const searchQuery = ref('')
const results = ref([])
const isLoading = ref(false)

// Debounce - delay the search
let debounceTimeout
watch(searchInput, (value) => {
  clearTimeout(debounceTimeout)
  debounceTimeout = setTimeout(() => {
    searchQuery.value = value
  }, 300)
})

The order of steps is worth memorizing: the debounceTimeout variable outside the watcher, then watch(searchInput, ...), inside it clearTimeout cancelling the previous countdown and setTimeout starting a new one. Every keystroke resets the clock, so only text followed by a pause reaches searchQuery. The field on screen still shows the letters immediately - only the search waits. The second watcher performs the actual request.

// Execute search
watch(searchQuery, async (query) => {
  if (!query) {
    results.value = []
    return
  }

  isLoading.value = true

  try {
    const response = await fetch(`/api/nova-lab/modules?q=${query}`)
    results.value = await response.json()
  } finally {
    isLoading.value = false
  }
})
</script>

The callback is async, and the try/finally block guarantees that isLoading returns to false even after a network error. Asynchrony has a price, though: if an older request comes back later than a newer one, it overwrites the fresh results. So in a production panel, add cleanup here with onCleanup and AbortController, just as in the lesson on stopping watchers.

Trajectory Calculator with History

The second panel computes an operation on velocity and time and keeps a history of results. The result is a value, so it goes into a computed, and a history entry is an action, so it goes into a watcher. The template contains two number fields, a list with the operation and the history.

<template>
  <div class="trajectory-calc" style="background: #0a0e27; color: #00ff88;">
    <label>Velocity (km/s):</label>
    <input v-model.number="velocity" type="number" style="background: #1a1e37; color: #00ff88;" />

    <label>Operation:</label>
    <select v-model="operation" style="background: #1a1e37; color: #00ff88;">
      <option value="+">Add</option>
      <option value="-">Subtract</option>
      <option value="*">Multiply</option>
      <option value="/">Divide</option>
    </select>

    <label>Time (s):</label>
    <input v-model.number="time" type="number" style="background: #1a1e37; color: #00ff88;" />
    <p style="color: #00b4d8;">= {{ result }}</p>

    <h3>Calculation history:</h3>
    <ul>
      <li v-for="(entry, i) in history" :key="i" style="color: #00b4d8;">{{ entry }}</li>
    </ul>
  </div>
</template>

The fields use v-model.number, so numbers rather than text reach the variables, and the history list renders its entries below the result. The first part of the script holds the panel state and the computed with the result.

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

const velocity = ref(25)
const time = ref(3600)
const operation = ref('*')
const history = ref([])

const result = computed(() => {
  switch (operation.value) {
    case '+': return velocity.value + time.value
    case '-': return velocity.value - time.value
    case '*': return velocity.value * time.value
    case '/': return time.value !== 0 ? velocity.value / time.value : 'Error'
    default: return 0
  }
})

The switch statement picks the operation, and when dividing by zero the computed returns the text Error instead of infinity. The second part of the script adds results to the history.

// Save to calculation history
watch(result, (newResult) => {
  const entry = `${velocity.value} ${operation.value} ${time.value} = ${newResult}`
  history.value.unshift(entry)

  // Limit to 10 entries
  if (history.value.length > 10) {
    history.value.pop()
  }
})
</script>

The watcher observes the result computed, because a computed is a perfectly valid source for watch. The unshift method adds an entry at the beginning of the array, and pop removes the oldest one once there are more than 10 entries. Note something less than obvious: when the velocity is 0, changing the time while multiplying adds no entry, because the result is still 0 and the watcher reacts only to a change of value.

Form Validation

The third panel is a registration form with an email address and a password. Computed alone is enough here, because every message and every button state is a value derived from what the user typed. The template binds the fields, shows errors and blocks the button.

<template>
  <form @submit.prevent="submit">
    <div>
      <input v-model="email" placeholder="Email" />
      <span v-if="emailError" class="error">{{ emailError }}</span>
    </div>

    <div>
      <input v-model="password" type="password" placeholder="Password" />
      <div class="strength" :class="passwordStrengthClass">
        Password strength: {{ passwordStrength }}
      </div>
    </div>

    <button :disabled="!isFormValid">Register</button>
  </form>
</template>

The button gets :disabled="!isFormValid", so it unlocks by itself once the form becomes valid, and :class switches the look of the password strength indicator. The first part of the script defines the fields and two computed messages.

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

const email = ref('')
const password = ref('')

const emailError = computed(() => {
  if (!email.value) return ''
  const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return regex.test(email.value) ? '' : 'Invalid email'
})

const passwordStrength = computed(() => {
  const pwd = password.value
  if (pwd.length < 6) return 'Weak'
  if (pwd.length < 10) return 'Medium'
  if (/[A-Z]/.test(pwd) && /[0-9]/.test(pwd)) return 'Strong'
  return 'Medium'
})

emailError first checks whether the field is empty, because an empty form should not shout an error before the user starts typing. Then a regular expression tests whether the address looks like "something@something.something" with no spaces. passwordStrength rates the password by its length and by the presence of an uppercase letter and a digit. The second part of the script builds on these results.

const passwordStrengthClass = computed(() => ({
  weak: passwordStrength.value === 'Weak',
  medium: passwordStrength.value === 'Medium',
  strong: passwordStrength.value === 'Strong'
}))

const isFormValid = computed(() => {
  return email.value &&
         !emailError.value &&
         password.value.length >= 6
})

function submit() {
  console.log('Form submitted')
}
</script>

passwordStrengthClass reads passwordStrength, and isFormValid reads emailError - that is a computed chain, in which each link recalculates only after the previous link changes. The same mechanism in its simplest form looks like this:

const price = ref(100)
const tax = computed(() => price.value * 0.23)
const total = computed(() => price.value + tax.value)

Changing price invalidates both computed values, and total recalculates with the new tax on its next read. The chain needs no watcher and no manual synchronization.

Debugging computed and watchers

When a computed does not recalculate when you expect it to, start with Vue DevTools. It is a browser extension, also available as a Vite plugin and as a standalone app, that shows the component tree and the state of each component, including the current values of refs and computed properties. For precise tracking there are the onTrack and onTrigger options, passed as the second argument of computed or among the options of watch.

const tax = computed(() => price.value * 0.23, {
  onTrack(event) {
    console.log('tracked', event.key)
  },
  onTrigger(event) {
    console.log('triggered', event.key, event.newValue)
  }
})

onTrack fires when the getter registers a dependency, and onTrigger when a change of that dependency invalidates the result, provided the computed is actually in use, for example in a template. Both options work only in development mode, so in the production build they cost nothing. I recommend DevTools first, and onTrack with onTrigger only when the state inspector is not enough. In the module project you will combine all of these tools in a single mission dashboard.

Remember: a computed answers the question "how much is it", and a watch answers "what to do when it changes" - mix up those roles, and the mission panel either calculates too much or does not react at all.

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

// NOVA LAB - Advanced Watching: Multiple Sources & Cleanup
const sensorA = ref(75)
const sensorB = ref(82)
const sensorC = ref(91)
const isMonitoring = ref(false)
const alerts = ref([])
const sensorReadings = ref([])

let monitoringInterval = null

// Watch multiple sources
watch([sensorA, sensorB, sensorC], ([a, b, c], [oldA, oldB, oldC]) => {
  const timestamp = new Date().toLocaleTimeString()

  if (a !== oldA) {
    alerts.value.unshift({
      time: timestamp,
      sensor: 'A',
      value: a,
      previous: oldA,
      color: '#00ff88'
    })
  }
  if (b !== oldB) {
    alerts.value.unshift({
      time: timestamp,
      sensor: 'B',
      value: b,
      previous: oldB,
      color: '#00b4d8'
    })
  }
  if (c !== oldC) {
    alerts.value.unshift({
      time: timestamp,
      sensor: 'C',
      value: c,
      previous: oldC,
      color: '#ffaa00'
    })
  }

  // Calculate average
  const avg = Math.round((a + b + c) / 3)
  if (avg < 70) {
    alerts.value.unshift({
      time: timestamp,
      sensor: 'SYSTEM',
      value: avg,
      message: 'Average below threshold!',
      color: '#ff0044'
    })
  }
})

// Watch with cleanup function
watch(isMonitoring, (newValue, oldValue, onCleanup) => {
  const timestamp = new Date().toLocaleTimeString()

  if (newValue) {
    alerts.value.unshift({
      time: timestamp,
      message: '▶Continuous monitoring started',
      color: '#00ff88'
    })

    // Start interval
    monitoringInterval = setInterval(() => {
      const reading = {
        time: new Date().toLocaleTimeString(),
        a: sensorA.value,
        b: sensorB.value,
        c: sensorC.value,
        avg: Math.round((sensorA.value + sensorB.value + sensorC.value) / 3)
      }
      sensorReadings.value.unshift(reading)

      // Simulate sensor fluctuation
      sensorA.value = Math.max(0, Math.min(100, sensorA.value + (Math.random() - 0.5) * 2))
      sensorB.value = Math.max(0, Math.min(100, sensorB.value + (Math.random() - 0.5) * 2))
      sensorC.value = Math.max(0, Math.min(100, sensorC.value + (Math.random() - 0.5) * 2))
    }, 2000)

    // Cleanup function - called when watcher stops or before re-run
    onCleanup(() => {
      if (monitoringInterval) {
        clearInterval(monitoringInterval)
        const stopTime = new Date().toLocaleTimeString()
        alerts.value.unshift({
          time: stopTime,
          message: '⏸Monitoring stopped (cleanup executed)',
          color: '#ffaa00'
        })
      }
    })
  }
})

// watchEffect for computed average
const avgReading = ref(0)
watchEffect(() => {
  avgReading.value = Math.round((sensorA.value + sensorB.value + sensorC.value) / 3)
})

function adjustSensor(sensor, delta) {
  if (sensor === 'A') {
    sensorA.value = Math.max(0, Math.min(100, sensorA.value + delta))
  } else if (sensor === 'B') {
    sensorB.value = Math.max(0, Math.min(100, sensorB.value + delta))
  } else if (sensor === 'C') {
    sensorC.value = Math.max(0, Math.min(100, sensorC.value + delta))
  }
}

function toggleMonitoring() {
  isMonitoring.value = !isMonitoring.value
}

function resetSensors() {
  sensorA.value = 75
  sensorB.value = 82
  sensorC.value = 91
}

function clearAlerts() {
  alerts.value = []
  sensorReadings.value = []
}

// Cleanup on unmount
onUnmounted(() => {
  if (monitoringInterval) {
    clearInterval(monitoringInterval)
  }
})
</script>

<template>
  <div class="advanced-watch">
    <div class="header">
      <h1>NOVA LAB Sensor Array</h1>
      <p class="subtitle">Multiple Sources & Watch Cleanup</p>
    </div>

    <div class="monitoring-control">
      <button
        @click="toggleMonitoring"
        :class="{ active: isMonitoring }"
        class="monitor-btn"
      >
        {{ isMonitoring ? '⏸Stop Monitoring' : '▶Start Monitoring' }}
      </button>
      <div class="status" :class="{ monitoring: isMonitoring }">
        {{ isMonitoring ? 'ACTIVE' : 'INACTIVE' }}
      </div>
    </div>

    <div class="sensors-grid">
      <div class="sensor-card sensor-a">
        <h3>Sensor A</h3>
        <div class="sensor-visual">
          <div
            class="sensor-bar"
            :style="{ height: sensorA + '%', background: '#00ff88' }"
          ></div>
        </div>
        <div class="sensor-value">{{ sensorA.toFixed(1) }}%</div>
        <div class="sensor-controls">
          <button @click="adjustSensor('A', -5)">-5</button>
          <button @click="adjustSensor('A', 5)">+5</button>
        </div>
      </div>

      <div class="sensor-card sensor-b">
        <h3>Sensor B</h3>
        <div class="sensor-visual">
          <div
            class="sensor-bar"
            :style="{ height: sensorB + '%', background: '#00b4d8' }"
          ></div>
        </div>
        <div class="sensor-value">{{ sensorB.toFixed(1) }}%</div>
        <div class="sensor-controls">
          <button @click="adjustSensor('B', -5)">-5</button>
          <button @click="adjustSensor('B', 5)">+5</button>
        </div>
      </div>

      <div class="sensor-card sensor-c">
        <h3>Sensor C</h3>
        <div class="sensor-visual">
          <div
            class="sensor-bar"
            :style="{ height: sensorC + '%', background: '#ffaa00' }"
          ></div>
        </div>
        <div class="sensor-value">{{ sensorC.toFixed(1) }}%</div>
        <div class="sensor-controls">
          <button @click="adjustSensor('C', -5)">-5</button>
          <button @click="adjustSensor('C', 5)">+5</button>
        </div>
      </div>

      <div class="sensor-card average">
        <h3>Average</h3>
        <div class="avg-display">{{ avgReading }}%</div>
        <div class="avg-status" :style="{
          color: avgReading > 80 ? '#00ff88' : avgReading > 60 ? '#ffaa00' : '#ff0044'
        }">
          {{ avgReading > 80 ? 'OPTIMAL' : avgReading > 60 ? 'CAUTION' : 'CRITICAL' }}
        </div>
      </div>
    </div>

    <div class="quick-actions">
      <button @click="resetSensors">Reset Sensors</button>
      <button @click="clearAlerts">Clear Logs</button>
    </div>

    <div class="data-panels">
      <div class="panel alerts-panel">
        <h3>Alert Log</h3>
        <div class="panel-content">
          <div
            v-for="(alert, index) in alerts.slice(0, 10)"
            :key="index"
            class="alert-item"
            :style="{ borderLeftColor: alert.color }"
          >
            <span class="alert-time">[{{ alert.time }}]</span>
            <span v-if="alert.sensor" class="alert-sensor">Sensor {{ alert.sensor }}:</span>
            <span v-if="alert.value !== undefined" class="alert-value">
              {{ alert.previous !== undefined ? `${alert.previous} → ` : '' }}{{ alert.value }}%
            </span>
            <span v-if="alert.message" class="alert-message">{{ alert.message }}</span>
          </div>
          <div v-if="alerts.length === 0" class="no-data">
            No alerts yet...
          </div>
        </div>
      </div>

      <div class="panel readings-panel">
        <h3>Sensor Readings (Auto-capture)</h3>
        <div class="panel-content">
          <div
            v-for="(reading, index) in sensorReadings.slice(0, 8)"
            :key="index"
            class="reading-item"
          >
            <span class="reading-time">[{{ reading.time }}]</span>
            <span class="reading-data">
              A: {{ reading.a.toFixed(1) }}% |
              B: {{ reading.b.toFixed(1) }}% |
              C: {{ reading.c.toFixed(1) }}% |
              Avg: {{ reading.avg }}%
            </span>
          </div>
          <div v-if="sensorReadings.length === 0" class="no-data">
            Start monitoring to capture readings...
          </div>
        </div>
      </div>
    </div>

    <div class="info-box">
      <strong>Advanced Watching:</strong> Watch multiple sources with <code>watch([a, b, c], ...)</code>.
      Use <code>onCleanup()</code> to clean up side effects like intervals when watcher stops!
    </div>
  </div>
</template>

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

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

.advanced-watch {
  max-width: 1200px;
  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;
}

.monitoring-control {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  margin-bottom: 30px;
}

.monitor-btn {
  padding: 15px 40px;
  font-size: 1.2rem;
  background: linear-gradient(135deg, #00b4d8 0%, #0077aa 100%);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-family: 'Courier New', monospace;
  font-weight: bold;
  transition: all 0.3s ease;
}

.monitor-btn.active {
  background: linear-gradient(135deg, #00ff88 0%, #00cc66 100%);
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%, 100% { box-shadow: 0 0 20px rgba(0, 255, 136, 0.5); }
  50% { box-shadow: 0 0 40px rgba(0, 255, 136, 0.8); }
}

.status {
  font-size: 1.5rem;
  font-weight: bold;
  color: #666;
}

.status.monitoring {
  color: #00ff88;
  text-shadow: 0 0 10px #00ff88;
}

.sensors-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.sensor-card {
  background: rgba(0, 180, 216, 0.05);
  border: 2px solid #00b4d8;
  border-radius: 10px;
  padding: 20px;
  text-align: center;
}

.sensor-card h3 {
  color: #00b4d8;
  margin-bottom: 15px;
}

.sensor-visual {
  height: 150px;
  background: rgba(0, 0, 0, 0.5);
  border: 2px solid #00ff88;
  border-radius: 8px;
  margin-bottom: 15px;
  display: flex;
  align-items: flex-end;
  justify-content: center;
  overflow: hidden;
}

.sensor-bar {
  width: 60%;
  transition: height 0.3s ease;
  border-radius: 5px 5px 0 0;
}

.sensor-value {
  font-size: 1.8rem;
  font-weight: bold;
  color: #00ff88;
  margin-bottom: 10px;
}

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

.sensor-controls button {
  background: #00b4d8;
  color: white;
  border: none;
  padding: 8px 15px;
  border-radius: 5px;
  cursor: pointer;
  font-family: 'Courier New', monospace;
  font-weight: bold;
}

.average {
  grid-column: span 1;
}

.avg-display {
  font-size: 3rem;
  font-weight: bold;
  color: #00ff88;
  text-shadow: 0 0 20px #00ff88;
  margin: 20px 0;
}

.avg-status {
  font-size: 1.2rem;
  font-weight: bold;
}

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

.quick-actions button {
  padding: 12px 30px;
  background: linear-gradient(135deg, #666 0%, #444 100%);
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-family: 'Courier New', monospace;
  font-weight: bold;
}

.data-panels {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(450px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

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

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

.panel-content {
  max-height: 300px;
  overflow-y: auto;
}

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

.alert-item {
  border-left: 4px solid;
}

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

.alert-time,
.reading-time {
  opacity: 0.7;
  margin-right: 8px;
}

.alert-sensor {
  color: #00b4d8;
  font-weight: bold;
  margin-right: 5px;
}

.alert-value {
  color: #00ff88;
}

.reading-data {
  color: #00b4d8;
}

.no-data {
  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;
}

code {
  background: rgba(0, 0, 0, 0.3);
  padding: 2px 8px;
  border-radius: 3px;
  color: #00b4d8;
}
</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. When is it better to use computed instead of watch?

  2. 2. When is it better to use watch instead of computed?

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

Hands-on tasks in the game

  • Code editor

    Complete the debounced search using watch to delay sending the query.

  • Click in order

    Arrange the correct import of computed and watch from Vue:

  • Vertical ordering

    Arrange the watch flush modes from earliest to latest execution:

  • Horizontal ordering

    Arrange the watch observing a reactive object property:

  • Click in order

    Arrange the watch observing multiple refs simultaneously:

  • Vertical ordering

    Arrange the steps for creating a computed property from start to finish:

  • Horizontal ordering

    Arrange the correct destructuring in watch on multiple sources:

  • Click in order

    Arrange watchEffect with onCleanup in the correct order:

  • Horizontal ordering

    Arrange the computed for email validation in the correct order:

  • Vertical ordering

    Arrange the steps for implementing debounce with watch from start to finish:

  • Click in order

    Arrange the computed dependency chain from source to final value:

  • Horizontal ordering

    Arrange the correct watchPostEffect call:

  1. QuestionWhen to use computed vs watch
  2. QuestionWhen to use watch vs computed
  3. QuestionReactivity debugging tool
  4. Coding taskPractice: Debounced Search with Watch
  5. QuestionSide effects in computed
  6. Click in orderImporting computed and watch
  7. QuestionwatchPostEffect
  8. Put in orderFlush order in watch
  9. QuestionWatch on getter function
  10. Put in orderWatch on getter
  11. QuestionCost of deep watch
  12. Click in orderWatch on multiple sources syntax
  13. Put in orderProcess of creating a computed property
  14. QuestionAsync in watch callback
  15. Put in orderWatch with multiple sources - destructuring
  16. QuestionDebugging computed
  17. QuestionDefault invocation of watch vs watchEffect
  18. Click in orderwatchEffect with cleanup syntax
  19. Put in orderComputed with form validation
  20. Put in orderDebounce pattern with watch
  21. Click in orderComputed chain - dependency chain
  22. Put in orderwatchPostEffect syntax

Useful articles