watch and the Search Feature
In this chapter you will learn to use watch and watchEffect to observe data changes and implement real-time filtering for the blog search box.
When Do You Need watch?
In most cases, Vue's reactive binding is sufficient: when data changes, the template updates automatically.
But some scenarios require you to actively execute a piece of logic when data changes, such as:
- After typing in the search box, filter the article list
- When the user switches categories, update the page title
- After data changes, store it in localStorage
- When a form field changes, perform form validation
This is when you need watch and watchEffect.
watch — Precise Watching
watch watches a specified data source and executes a callback when the data changes.
You can get the new value and the old value to do comparative processing.
Example
Current search: {{ keyword }}
Three Data Sources for watch
| Data Source Type | Syntax | Example |
|---|---|---|
| A single ref | watch(ref, callback) | watch(keyword, fn) |
| A property of a reactive object | watch(() => obj.prop, callback) | watch(() => user.name, fn) |
| Multiple data sources | watch([ref1, ref2], callback) | watch([kw, cat], fn) |
Example
import
{
ref
,
watch
}
from
'vue'
const
keyword
=
ref
(
''
)
const
category
=
ref
(
'All'
)
// Watch a single ref
watch
(
keyword
,
(
newVal
)
=>
{
document.
title
=
newVal
?
`Search: $
{
newVal
}
`
:
'RUNOOB Blog'
}
)
// Watch multiple data sources
watch
(
[
keyword
,
category
]
,
(
[
newKw
,
newCat
]
,
[
oldKw
,
oldCat
]
)
=>
{
console.
log
(
'Keyword or category changed; re-filter articles'
)
// Execute filtering logic...
}
)
watch is by defaultlazy execution— it does not trigger when the data first gets a value; only subsequent changes trigger it. If you need it to run once during initialization as well, add the
{ immediate: true }configuration option.
watchEffect — Automatically Tracks Dependencies
watchEffect does not require manually specifying a data source; it automatically tracks the reactive data used in the callback.
The biggest difference from watch: watchEffect executes once immediately.
Example
{{ a.title }}
watch vs watchEffect Comparison
| Feature | watch | watchEffect |
|---|---|---|
| Whether to Specify a Data Source | Manually specified | Automatically tracks dependencies |
| Initial Execution | Not executed by default (immediate can be configured) | Executes immediately |
| Getting the Old Value | Can get the old value | Cannot get the old value |
| Applicable scenarios | Need to compare old and new values; precisely control timing | Don't care about old/new values; just want to "respond to changes" |
Simple rule: if your logic is "when X changes, do Y", use watch. If your logic is "whenever a dependency changes, recompute the result", use watchEffect or computed. In practice, data that can be computed should prefer computed; watch is for handling "side effects" — such as calling an API, storing locally, or manipulating the DOM.
Debounce Approach
Each keystroke in the search box triggers filtering; for local data this is fine, but if every input sends a network request, it causes a lot of waste.
The idea of Debounce: wait until the user stops typing for a while, then perform the operation.
Example
import
{
ref
,
watch
}
from
'vue'
const
keyword
=
ref
(
''
)
const
filteredArticles
=
ref
(
[
]
)
let timer
=
null
// Timer ID
watch
(
keyword
,
(
newVal
)
=>
{
// Clear the previous timer
clearTimeout
(
timer
)
// Only execute filtering if no new input change occurs within 300ms
timer
=
setTimeout
(
(
)
=>
{
filteredArticles.
value
=
articles.
value
.
filter
(
a
=>
a.
title
.
includes
(
newVal
)
||
a.
summary
.
includes
(
newVal
)
)
}
,
300
)
}
)
For this blog project, the data is local, so debounce is not necessary. But understanding this approach is very helpful for larger projects later.
Hands-On: Add Real-Time Search to the Blog
Add a search box to the NavBar component to filter article titles and summaries in real time as keywords are entered.
Example
:categories="categories" :active-category="activeCategory" @update-category="handleCategoryChange" /> Loading... No matching articles found v-for="article in filteredArticles" :key="article.id" :id="article.id" :title="article.title" :summary="article.summary" :date="article.date" :category="article.category" />
Now search and category filtering can work together — after searching keywords, clicking a category button stacks the filtering. Both conditions are reactive, so filteredArticles updates automatically whenever either changes.
Chapter Summary
In this chapter you mastered the usage of watch (manually specify data source, can get new/old values) and watchEffect (automatically track dependencies, execute immediately), and learned to use computed to achieve stacked filtering of search + category.
The real-time filtering experience of the search box is much smoother than "type then click a button" — this is the value of the reactive system.