Middle
What can you say about computed and watch in Vue 3?
sobes.tech AI
Answer from AI
In Vue 3, computed and watch are reactive tools for working with data, but with different purposes.
-
computed — these are computed properties that are cached and recalculated only when their dependencies change. They are used to compute values based on reactive data, with Vue optimizing performance by avoiding unnecessary calculations.
import { ref, computed } from 'vue'; const count = ref(1); const double = computed(() => count.value * 2); -
watch — this is an observer that monitors changes in reactive data and performs side effects, such as asynchronous operations or API calls. Unlike computed, watch is not cached and is intended for reacting to changes.
import { ref, watch } from 'vue'; const count = ref(1); watch(count, (newVal, oldVal) => { console.log(`count changed from ${oldVal} to ${newVal}`); });
In summary, computed is for calculating values with caching, watch is for reacting to changes with side effects.