Vue.js question detail
What is watch() and how is it used?
The watch() function observes a reactive source((like ref, reactive, getter functions or computed values)) and
runs a callback function whenever that source changes.
Syntax:
watch(source, callback, options ?)
- source: a ref, reactive property, getter function, or array of them.
- callback(newValue, oldValue): function to run when the value changes.
- options (optional): object to control behavior (e.g., immediate, deep).
Example 1: Watching a ref
import {ref, watch} from 'vue';
const count = ref(0);
watch(count, (newVal, oldVal) => {
console.log(`Count changed from ${oldVal} to ${newVal}`);
});
count.value = 5; // triggers the watch callback
Example 2: Watching a function (getter)
const firstName = ref('Sudheer');
const lastName = ref('Jonna');
watch(
() => `${firstName.value} ${lastName.value}`,
(newFullName, oldFullName) => {
console.log(`Full name changed from ${oldFullName} to ${newFullName}`);
}
);
Example 3: Watching a reactive object deeply
import {reactive, watch} from 'vue';
const user = reactive({name: 'Sudheer', age: 38});
watch(
() => user,
(newUser, oldUser) => {
console.log('User object changed:', newUser);
},
{deep: true}
);
The main uses of watch() are:
- Watching route changes
- Triggering API calls
- Responding to complex data changes
- Manually reacting to specific state updates