Thuta Learning
Vue.js
BasicWeb Developmentbeginner

Computed Properties and Watchers

What you'll walk away with

  • Build a computed value
  • Know when to use watch versus computed

Let's break it down simply

computed() is a derived value whose result is cached until its dependencies change. Use watch() for side effects like API calls, local storage, or logging. Instead of writing complicated calculations in the template, use computed.

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

const price = ref(12000)
const quantity = ref(2)
const total = computed(() => price.value * quantity.value)

watch(quantity, (next, previous) => {
  console.log(`Quantity: ${previous} → ${next}`)
})
</script>

<template><strong>Total: {{ total }} MMK</strong></template>
You should see
Total: 24000 MMK

Try it yourself

Calculate the average score from a score list using computed. Log a message with watch every time a score changes.

Computed Properties — Vue.js

Easy traps

  • Making an API call inside a computed getter
  • Using watch to duplicate state for a simple derived value

Exercise

Calculate the average score from a score list using computed. Log a message with watch every time a score changes.

You'll know it worked when: Total: 24000 MMK

Computed Properties and Watchers | Thuta Learning