YouTip LogoYouTip

Vue3 Blog Watch Search

In this chapter, you will learn to use watch and watchEffect to listen for data changes, and implement real-time filtering for the blog search box. * * * ## What scenarios require watch? In most cases, Vue's reactive binding is sufficient: when data changes, the template updates automatically. But there are scenarios where you need to actively execute logic when data changes, such as: * Filter article list after search box input * Update page title when user switches categories * Save to localStorage after data changes * Perform form validation when form fields change This is when watch and watchEffect are needed. * * * ## watch β€” Precise Listening watch listens to a specified data source and executes a callback function when the data changes. You can get the new value and old value for comparison processing. ## Example ### Three Data Source Types for watch | Data Source Type | Syntax | Example | | --- | --- | --- | | Single ref | watch(ref, callback) | `watch(keyword, fn)` | | Reactive object property | 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') // Listen to single ref watch(keyword,(newVal)=>{ document.title= newVal ? `Search:${newVal}` :'TUTORIAL Blog' }) // Listen to multiple data sources watch([keyword, category],([newKw, newCat],[oldKw, oldCat])=>{ console.log('When keywords or categories change, re-filter articles') // Execute filtering logic... }) > watch is lazy by default β€” it doesn't trigger when data first has a value, only on subsequent changes. If you need it to execute on initialization as well, add the `{ immediate: true }` option. * * * ## watchEffect β€” Automatic Dependency Tracking watchEffect doesn't require manually specifying a data source; it automatically tracks reactive data used in the callback. The biggest difference from watch: watchEffect executes immediately once. ## Example ### watch vs watchEffect Comparison | Feature | watch | watchEffect | | --- | --- | --- | | Specify data source | Manual | Automatic dependency tracking | | Initial execution | Does not execute by default (can configure immediate) | Executes immediately | | Get old value | Can get old value | Cannot get old value | | Use case | Need to compare old/new values, precise timing control | Don't care about old/new values, just want to "respond to changes" | > Simple selection method: If your logic is "when X changes, do Y", use watch. If your logic is "whenever any dependency changes, recalculate the result", use watchEffect or computed. Actually, data that can be computed shouldPrioritize using computed, and watch is used to handle "side effects" β€” like calling APIs, saving locally, manipulating DOM. * * * ## Debounce Concept Search box filtering triggers on every key press, which is fine for local data, but if each input sends a network request, it causes a lot of waste. The idea of Debounce is: wait for the user to stop input for a period of time before executing the operation. ## Example import{ ref, watch } from 'vue' const keyword = ref('') const filteredArticles = ref([]) let timer =null// Timer ID watch(keyword,(newVal)=>{ // Clear previous timer clearTimeout(timer) // Only execute filtering if no new input within 300ms timer = setTimeout(()=>{ filteredArticles.value= articles.value.filter( a => a.title.includes(newVal)|| a.summary.includes(newVal) ) },300) }) For this blog project, data is local, so debounce is not required. But understanding this concept will be very helpful for larger projects later. * * * ## Hands-on: Add Real-time Search to the Blog Add a search box in the NavBar component to filter article titles and summaries in real-time. ## Example
← Django Blog Forms FavoritesDjango Blog Filter Search β†’