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.
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.
Watchers are most useful when you want to perform asynchronous or expensive operations.
Common use cases include:
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.
watch: {
question(newValue, oldValue) {
if (newValue.includes('?')) {
this.getAnswer()
}
}
}
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.
watch: {
someObject: {
handler(newValue, oldValue) {
// This fires even if someObject.nestedProperty changes
},
deep: true
}
}
When should you prefer using a Watcher over a Computed Property?