Vue Watchers

👀 Vue Watchers

In Vue.js, watchers are used to observe changes in data and perform actions (side effects) when those changes occur.

 What are Vue Watchers?

A watcher allows you to run code when a specific reactive property changes.

✔ Ideal for:

  • API calls

  • Logging

  • Debounced actions

  • Responding to data changes

❌ Not ideal for calculations (use computed instead)


 Basic Syntax

watch: {
property(newValue, oldValue) {
// logic here
}
}

 Example 1: Simple Watcher

<div id="app">
<input v-model="name">
<p>{{ name }}</p>
</div>
watch: {
name(newVal, oldVal) {
console.log("Old:", oldVal, "New:", newVal)
}
}

📌 Runs every time name changes.


 Example 2: Watching for API Call

watch: {
search(newVal) {
this.fetchResults(newVal)
}
},
methods: {
fetchResults(query) {
console.log("Fetching for:", query)
}
}

✔ Perfect use case for watchers.


 Example 3: Immediate Watcher

Runs as soon as the component loads.

watch: {
username: {
handler(newVal) {
console.log("Username:", newVal)
},
immediate: true
}
}

 Example 4: Deep Watcher

Used for objects & arrays.

data() {
return {
user: {
name: "Amit",
age: 22
}
}
},
watch: {
user: {
handler(newVal) {
console.log("User changed", newVal)
},
deep: true
}
}

📌 Without deep: true, Vue won’t detect nested changes.


 Example 5: Watching Multiple Properties

watch: {
firstName() {
this.updateName()
},
lastName() {
this.updateName()
}
}

 Example 6: Using watch as a Method

watch: {
count: 'countChanged'
},
methods: {
countChanged(newVal) {
console.log("Count:", newVal)
}
}

 Watchers vs Computed (Important ⚠️)

Feature Watcher Computed
Purpose Side effects Derived data
Cached ❌ No ✔ Yes
API Calls ✔ Yes ❌ No
Return value ❌ No ✔ Yes

✔ Use watchers for effects
✔ Use computed for values


 Common Use Cases

  • Auto-save form data

  • Search suggestions

  • API calls on input change

  • Data validation

  • Analytics tracking


 Common Mistakes ❌

❌ Using watchers instead of computed
❌ Heavy logic inside watcher
❌ Forgetting deep: true for objects


 Best Practices ✅

✔ Keep watchers lightweight
✔ Avoid mutating watched property inside watcher
✔ Use immediate carefully
✔ Prefer computed when possible


 Summary Table

Scenario Use
Derived value Computed
API call Watcher
Side effects Watcher
Validation Watcher
Filtering Computed

 Conclusion

Vue watchers are powerful tools for reacting to data changes.
Use them wisely for side effects, not for calculations.

You may also like...