We use cookies to enhance your experience on the site
CodeWorlds

Computed Properties - Automatic Calculations

Welcome to the NOVA LAB Computation Center! Dr. Nova says: just as our computers automatically calculate flight trajectories to Mars, computed properties automatically recalculate values when input data changes.

What are Computed Properties?

Computed are reactive properties that automatically update when their dependencies change - like a navigation system recalculating course with every parameter change.

1<template>
2  <div class="navigation-panel" style="background: #0a0e27; color: #00ff88;">
3    <p>Velocity: {{ velocity }} km/s</p>
4    <p>Time: {{ timeElapsed }} s</p>
5    <p>Distance: {{ distanceTraveled }} km</p>
6  </div>
7</template>
8
9<script setup>
10import { ref, computed } from 'vue'
11
12const velocity = ref(25)
13const timeElapsed = ref(3600)
14
15// Computed - automatically recalculates distance
16const distanceTraveled = computed(() => {
17  return velocity.value * timeElapsed.value
18})
19</script>

Computed vs Methods

1<template>
2  <div class="fuel-display" style="background: #0a0e27; color: #00ff88;">
3    <!-- Computed - called without () -->
4    <p>{{ fuelStatus }}</p>
5
6    <!-- Method - called with () -->
7    <p>{{ getFuelStatus() }}</p>
8  </div>
9</template>
10
11<script setup>
12import { ref, computed } from 'vue'
13
14const fuelLevel = ref(750)
15const maxFuel = ref(1000)
16
17// Computed - cached, recalculated only when dependencies change
18const fuelStatus = computed(() => {
19  console.log('Computed executed')
20  const percentage = (fuelLevel.value / maxFuel.value) * 100
21  return `Fuel: ${percentage.toFixed(1)}%`
22})
23
24// Method - executed on every render
25function getFuelStatus() {
26  console.log('Method executed')
27  const percentage = (fuelLevel.value / maxFuel.value) * 100
28  return `Fuel: ${percentage.toFixed(1)}%`
29}
30</script>

Computed Caching

1<script setup>
2import { ref, computed } from 'vue'
3
4const sensorReadings = ref([25, 30, 28, 32, 29])
5
6// Expensive operation - but cached!
7const averageTemperature = computed(() => {
8  console.log('Calculating average temperature...')
9  return sensorReadings.value.reduce((sum, reading) => {
10    // Simulating expensive operation
11    return sum + reading
12  }, 0) / sensorReadings.value.length
13})
14
15// Multiple references - only one calculation
16// {{ averageTemperature }}
17// {{ averageTemperature }}
18// {{ averageTemperature }}
19</script>
Go to CodeWorlds