FrontendDeveloper.in

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:

  1. Watching route changes
  2. Triggering API calls
  3. Responding to complex data changes
  4. Manually reacting to specific state updates
Back to all Vue.js questions
Get LinkedIn Premium at Rs 399