Vue.js course ยท Module 4: Computed & Watch
Computed Properties - Automatic Calculations
In this lesson5
Welcome to the NOVA LAB Computation Center! The duty navigator has two numbers on the panel: the ship's velocity and the flight time. The third one, the distance traveled, gets recalculated by hand after every course correction. One forgotten update is enough for the panel to show a distance from an hour ago, and nobody notices. Dr. Nova has a simple rule for this: a value that can be derived from other data should calculate itself. In Vue, that job belongs to computed properties.
What you will learn
- computed - derived values that recalculate on their own and remember the result.
- computed with a getter and a setter - two-way fields, such as an energy unit converter.
- watch - reacting to changes: a log entry, a server request, an alarm.
- watchEffect - a watcher that works out by itself which data it uses.
- stopping watchers and cleanup - closing telemetry channels once they are no longer needed.
- practice and a project - a mission dashboard that combines all of these tools.
What are Computed Properties?
You import the computed function from the vue package, just like ref. You pass it a getter, an arrow function that returns the result of a calculation. In return you get an object similar to a ref: in the script you read its result through .value, and in the template simply by its name. Below is a navigation panel with two inputs stored in refs and one computed that calculates the distance.
<template>
<div class="navigation-panel" style="background: #0a0e27; color: #00ff88;">
<p>Velocity: {{ velocity }} km/s</p>
<p>Time: {{ timeElapsed }} s</p>
<p>Distance: {{ distanceTraveled }} km</p>
</div>
</template>
<script setup>
import { ref, computed } from 'vue'
const velocity = ref(25)
const timeElapsed = ref(3600)
// Computed - automatically recalculates distance
const distanceTraveled = computed(() => {
return velocity.value * timeElapsed.value
})
</script>The getter multiplies velocity.value by timeElapsed.value, and Vue remembers which reactive values it read along the way. Those are the computed's dependencies. When you change the velocity from 25 to 30, the distance paragraph shows 108000 without a single extra line of code. Notice what did not change: velocity and timeElapsed are still ordinary refs, and the computed never writes to them, it only reads them. You cannot assign a value to the computed itself either - by default it is read-only, and an attempt to write ends with a warning in the console. The pattern worth memorizing always looks like this: const total = computed(() => a.value + b.value).
Computed vs Methods
You could produce the same text with a plain function called in the template. Both routes display identical text on the panel, so the difference lies elsewhere: in when the code runs. Below is a fuel indicator built both ways, with a console.log in each so you can see every run.
<template>
<div class="fuel-display" style="background: #0a0e27; color: #00ff88;">
<!-- Computed - called without () -->
<p>{{ fuelStatus }}</p>
<!-- Method - called with () -->
<p>{{ getFuelStatus() }}</p>
</div>
</template>
<script setup>
import { ref, computed } from 'vue'
const fuelLevel = ref(750)
const maxFuel = ref(1000)
// Computed - cached, recalculated only when dependencies change
const fuelStatus = computed(() => {
console.log('Computed executed')
const percentage = (fuelLevel.value / maxFuel.value) * 100
return `Fuel: ${percentage.toFixed(1)}%`
})
// Method - executed on every render
function getFuelStatus() {
console.log('Method executed')
const percentage = (fuelLevel.value / maxFuel.value) * 100
return `Fuel: ${percentage.toFixed(1)}%`
}
</script>In the template you write a computed without parentheses, because it is a value, and a method with parentheses, because it is a call. A method runs on every render of the component, even when the render was caused by a change in a completely unrelated field. A computed runs its getter only when fuelLevel or maxFuel changes, and on every other render it hands back the remembered result. Let us bust three myths while we are here. A computed is not "always faster" - the whole gain comes from remembering the result. A computed takes no arguments - when you need a parameter, reach for a method. And a computed does not work asynchronously: the getter must return a value right away, so await and server requests have no place in it.
Computed Caching
The remembered result is the cache. It pays off most with expensive calculations, such as averaging hundreds of sensor readings. In the example, the array method reduce walks through the readings and adds them up into one number, which we then divide by the number of readings.
<script setup>
import { ref, computed } from 'vue'
const sensorReadings = ref([25, 30, 28, 32, 29])
// Expensive operation - but cached!
const averageTemperature = computed(() => {
console.log('Calculating average temperature...')
return sensorReadings.value.reduce((sum, reading) => {
// Simulating expensive operation
return sum + reading
}, 0) / sensorReadings.value.length
})
// Multiple references - only one calculation
// {{ averageTemperature }}
// {{ averageTemperature }}
// {{ averageTemperature }}
</script>The three comments with {{ averageTemperature }} stand in for three places in the template that display the average. Despite three references, the message about calculating the average appears in the console once. And what happens when a new reading arrives in sensorReadings? Vue does not recalculate the average immediately. First it marks the computed as stale - in the Vue source code this flag is called "dirty". The getter runs only on the next read of the value, and the new result goes into the cache and is returned. If nobody reads the average, the getter does not run at all. Remember as well that only reactive data can be a dependency: a computed based on Date.now() would never refresh.
Filtering the module list
A typical job for a computed is a list filtered by whatever the operator typed into the search box. The filter method keeps only the array elements that meet a condition, toLowerCase converts text to lowercase, and includes checks whether a name contains the search fragment.
import { ref, computed } from 'vue'
const searchQuery = ref('')
const modules = ref([
{ id: 1, name: 'Life Support System' },
{ id: 2, name: 'Oxygen Recycler' }
])
const filteredModules = computed(() => {
const query = searchQuery.value.toLowerCase()
return modules.value.filter((mod) => mod.name.toLowerCase().includes(query))
})This computed has two dependencies, searchQuery and modules, so the list refreshes both after a letter is typed and after a new module is added. Because both sides are converted to lowercase, letter case stops mattering. The original array does not change, because filter always returns a new one, and an empty search box lets every module through, since every name contains the empty fragment.
I recommend a simple rule: anything that can be derived from other data belongs in a computed, not in a separate ref that you update by hand. A single source of truth means fewer places where an update can be forgotten. In the next lesson you will teach a computed to accept writes, and after that you will meet watch - the tool for moments when you need an action rather than a value.
Remember: a computed is the station's navigation computer - it recalculates the course only when one of the parameters changes, and between changes it reports the remembered result.
Code for this lesson: App.vue
<script setup>
import { ref, computed } from 'vue'
// NOVA LAB Control Center - Mission Statistics
const missionDays = ref(127)
const crewMembers = ref(8)
const oxygenLevel = ref(87)
const powerOutput = ref(2400)
const waterReserves = ref(3200)
// Computed properties - automatically recalculated
const missionWeeks = computed(() => {
return Math.floor(missionDays.value / 7)
})
const oxygenPerPerson = computed(() => {
return (oxygenLevel.value / crewMembers.value).toFixed(1)
})
const powerPerPerson = computed(() => {
return Math.floor(powerOutput.value / crewMembers.value)
})
const systemStatus = computed(() => {
if (oxygenLevel.value > 80 && powerOutput.value > 2000) {
return 'OPTIMAL'
} else if (oxygenLevel.value > 60 && powerOutput.value > 1500) {
return 'CAUTION'
}
return 'CRITICAL'
})
const statusColor = computed(() => {
const colors = {
'OPTIMAL': '#00ff88',
'CAUTION': '#ffaa00',
'CRITICAL': '#ff0044'
}
return colors[systemStatus.value]
})
function adjustOxygen(delta) {
oxygenLevel.value = Math.max(0, Math.min(100, oxygenLevel.value + delta))
}
function adjustPower(delta) {
powerOutput.value = Math.max(0, powerOutput.value + delta)
}
</script>
<template>
<div class="control-center">
<div class="header">
<h1>NOVA LAB Control Center</h1>
<div class="mission-time">Sol {{ missionDays }} (Week {{ missionWeeks }})</div>
</div>
<div class="status-panel" :style="{ borderColor: statusColor }">
<h2>System Status: <span :style="{ color: statusColor }">{{ systemStatus }}</span></h2>
<div class="crew-info">Crew: {{ crewMembers }} members</div>
</div>
<div class="stats-grid">
<div class="stat-card">
<div class="stat-label">Oxygen Level</div>
<div class="stat-value">{{ oxygenLevel }}%</div>
<div class="stat-computed">{{ oxygenPerPerson }}% per person</div>
<div class="controls">
<button @click="adjustOxygen(-5)">-5%</button>
<button @click="adjustOxygen(5)">+5%</button>
</div>
</div>
<div class="stat-card">
<div class="stat-label">Power Output</div>
<div class="stat-value">{{ powerOutput }}W</div>
<div class="stat-computed">{{ powerPerPerson }}W per person</div>
<div class="controls">
<button @click="adjustPower(-100)">-100W</button>
<button @click="adjustPower(100)">+100W</button>
</div>
</div>
<div class="stat-card">
<div class="stat-label">Water Reserves</div>
<div class="stat-value">{{ waterReserves }}L</div>
<div class="stat-computed">{{ (waterReserves / crewMembers).toFixed(1) }}L per person</div>
</div>
</div>
<div class="info-box">
<strong>Computed Properties:</strong> Values automatically update when dependencies change!
</div>
</div>
</template>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Courier New', monospace;
background: #0a0e27;
color: #00ff88;
padding: 20px;
}
.control-center {
max-width: 900px;
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;
}
.mission-time {
color: #00b4d8;
font-size: 1.2rem;
}
.status-panel {
padding: 20px;
margin-bottom: 30px;
background: rgba(0, 255, 136, 0.05);
border: 2px solid;
border-radius: 10px;
text-align: center;
transition: all 0.3s ease;
}
.status-panel h2 {
font-size: 1.5rem;
margin-bottom: 10px;
}
.crew-info {
color: #00b4d8;
font-size: 1.1rem;
}
.stats-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
margin-bottom: 30px;
}
.stat-card {
background: rgba(0, 180, 216, 0.05);
border: 2px solid #00b4d8;
border-radius: 10px;
padding: 20px;
text-align: center;
}
.stat-label {
color: #00b4d8;
font-size: 0.9rem;
margin-bottom: 10px;
text-transform: uppercase;
}
.stat-value {
font-size: 2.5rem;
font-weight: bold;
color: #00ff88;
margin-bottom: 10px;
text-shadow: 0 0 10px #00ff88;
}
.stat-computed {
color: #ffaa00;
font-size: 1rem;
margin-bottom: 15px;
font-style: italic;
}
.controls {
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 {
background: linear-gradient(135deg, #00ff88 0%, #00cc66 100%);
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(0, 255, 136, 0.3);
}
button:active {
transform: translateY(0);
}
.info-box {
background: rgba(0, 255, 136, 0.1);
border: 2px solid #00ff88;
border-radius: 10px;
padding: 15px;
text-align: center;
color: #00ff88;
}
</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. What is a computed property in Vue.js?
2. What is the main advantage of computed properties over regular methods?
These are 2 of 3 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
Complete the code - create a computed property that calculates distance based on speed and time.
- Click in order
Arrange the correct syntax for creating a computed property:
- Code editor
Complete the computed property that filters a list of modules based on the entered query.
- Vertical ordering
Arrange the stages of computed property operation from data change to result: