Vue.js Lesson 5: Computed & Watch
Computed properties derive values from reactive state automatically. Watchers run side effects when state changes.
Computed Properties
<script setup>
import { ref, computed } from "vue";
const firstName = ref("Alice");
const lastName = ref("Smith");
const items = ref([10, 20, 30, 40]);
// Computed: auto-updates when dependencies change
const fullName = computed(() => `${firstName.value} ${lastName.value}`);
const total = computed(() => items.value.reduce((a, b) => a + b, 0));
const average = computed(() => total.value / items.value.length);
// Computed with getter AND setter
const fullNameRW = computed({
get: () => `${firstName.value} ${lastName.value}`,
set: (val) => {
const [first, last] = val.split(" ");
firstName.value = first;
lastName.value = last;
}
});
</script>
watch & watchEffect
<script setup>
import { ref, watch, watchEffect } from "vue";
const query = ref("");
const results = ref([]);
// watch: explicit source + callback
watch(query, async (newQuery, oldQuery) => {
if (newQuery.length < 2) { results.value = []; return; }
results.value = await searchAPI(newQuery);
}, { immediate: true, debounce: 300 });
// watchEffect: auto-tracks dependencies
const count = ref(0);
watchEffect(() => {
document.title = `Count: ${count.value}`; // tracks count automatically
});
</script>
🏋️ Practice Task
Build a shopping cart. Items array: ref([{id,name,price,qty}]). Computed: subtotal (sum of price*qty), tax (subtotal * 0.08), total (subtotal + tax), itemCount (sum of qty). Watch total — when it exceeds $100, show a “Free shipping!” badge.
💡 Hint: computed(() => items.value.reduce((sum, item) => sum + item.price * item.qty, 0))