Sobes.tech
Middle

What is the purpose of a watch with the deep option?

sobes.tech AI

Answer from AI

The deep option in watch (for example, in Vue.js) is used to track changes within nested objects or arrays. By default, watch only reacts to the replacement of the variable's value, not to changes in the properties inside the object.

When deep: true is set, the watcher recursively tracks all nested properties, and any change within the object or array triggers the callback.

Example:

watch(
  () => user,
  (newVal, oldVal) => {
    console.log('User data changed');
  },
  { deep: true }
);

// If user = { name: 'Ivan', address: { city: 'Moscow' } }
// and user.address.city changes, the watch will only trigger with deep: true

This is useful when you need to react to any changes in complex data structures.