Vue Watchers
👀 Vue Watchers
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
Example 1: Simple Watcher
📌 Runs every time name changes.
Example 2: Watching for API Call
✔ Perfect use case for watchers.
Example 3: Immediate Watcher
Runs as soon as the component loads.
Example 4: Deep Watcher
Used for objects & arrays.
📌 Without deep: true, Vue won’t detect nested changes.
Example 5: Watching Multiple Properties
Example 6: Using watch as a Method
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.
