CodexBloom - Programming Q&A Platform

Vue 3: How to efficiently filter a large list with v-for when using a watcher?

๐Ÿ‘€ Views: 259 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-16
vue.js performance computed-properties watchers input-debouncing JavaScript

I need help solving I'm stuck on something that should probably be simple... I'm working on a Vue 3 application where I need to display a large list of items (around 10,000 entries) and provide a search functionality to filter through them. The list is stored in a reactive data property called `items`, and I want to filter this list based on user input from a text input bound to `searchQuery` using v-model. I've set up a computed property that filters the items based on `searchQuery`, but I'm experiencing significant lag when typing in the input field, especially as the list size increases. Hereโ€™s a simplified version of my code: ```vue <template> <div> <input v-model="searchQuery" placeholder="Search items..." /> <ul> <li v-for="item in filteredItems" :key="item.id">{{ item.name }}</li> </ul> </div> </template> <script> import { ref, computed } from 'vue'; export default { setup() { const items = ref([...Array(10000).keys()].map(i => ({ id: i, name: `Item ${i}` }))); // large items array const searchQuery = ref(''); const filteredItems = computed(() => { return items.value.filter(item => item.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ); }); return { items, searchQuery, filteredItems }; } }; </script> ``` Iโ€™ve also tried using a watcher instead of a computed property, but that didnโ€™t help much either: ```javascript watch(searchQuery, (newQuery) => { filteredItems.value = items.value.filter(item => item.name.toLowerCase().includes(newQuery.toLowerCase()) ); }); ``` The filtering seems to be blocking the UI, causing a noticeable delay. I even attempted debouncing the input, but it still feels sluggish. I'm wondering if there are best practices or optimization techniques specific to Vue.js that could help improve the performance during this filtering process. Any suggestions would be greatly appreciated! This is part of a larger API I'm building. What am I doing wrong? My development environment is Ubuntu 20.04. I'd really appreciate any guidance on this.