Vue Watchers

Vue Watchers

Computed properties are perfect for calculating declarative values synchronously.

However, there are times when you need to perform "side effects" in reaction to state changes.

This is exactly where Vue Watchers come into play.


What is a Watcher?

A watcher allows you to observe a specific reactive data property.

When that property changes, the watcher function is triggered automatically.

Watchers are defined inside the watch object of your Vue component.


When to use Watchers

Watchers are most useful when you want to perform asynchronous or expensive operations.

Common use cases include:


Basic Watcher Example

To watch a property, you create a function inside watch that has the exact same name as the data property.

The function receives two arguments: the newValue and the oldValue.

Basic Watch Example:

watch: {
  question(newValue, oldValue) {
    if (newValue.includes('?')) {
      this.getAnswer()
    }
  }
}

Deep Watching

By default, watchers are shallow.

If you watch an object, the watcher will not trigger if a nested property inside the object is mutated.

To force the watcher to trigger on deep mutations, you must configure it as an object with deep: true.

Deep Watcher Syntax:

watch: {
  someObject: {
    handler(newValue, oldValue) {
      // This fires even if someObject.nestedProperty changes
    },
    deep: true
  }
}

Exercise 1 of 1

?

When should you prefer using a Watcher over a Computed Property?