Performance: Debounced watchers pattern
This pattern affects how often the UI updates in response to data changes, impacting interaction responsiveness and CPU usage.
import { watch } from 'vue'; import { debounce } from 'lodash-es'; const debouncedFetch = debounce((val) => { fetchResults(val); }, 300); watch(searchTerm, (newVal) => { debouncedFetch(newVal); });
import { watch } from 'vue'; watch(searchTerm, (newVal) => { fetchResults(newVal); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Immediate watcher | Many updates per input | 1 reflow per input change | High paint cost due to frequent updates | [X] Bad |
| Debounced watcher | Few updates after input pauses | 1 reflow per pause | Lower paint cost with fewer updates | [OK] Good |
import { ref, watch } from 'vue';
import { debounce } from 'lodash-es';
const search = ref('');
watch(search, debounce((newVal) => {
console.log('Search:', newVal);
}, 300));import { ref, watch } from 'vue';
import { debounce } from 'lodash-es';
const query = ref('');
watch(query, () => {
debounce(() => {
console.log('Query:', query.value);
}, 500)();
});import { ref, watch } from 'vue';
import { debounce } from 'lodash-es';
const searchTerm = ref('');
// What is the correct watcher setup?Pass the test and this pattern moves unknown