CodexBloom - Programming Q&A Platform

Vue 3: How to optimize rendering performance when using multiple v-for loops with filtered arrays?

๐Ÿ‘€ Views: 1656 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-16
vue.js performance v-for computed-properties JavaScript

I've been struggling with this for a few days now and could really use some help. I'm maintaining legacy code that I've looked through the documentation and I'm still confused about I'm facing significant performance issues in my Vue 3 application when rendering a list of items with multiple nested `v-for` loops. I've noticed that as the number of items grows, the rendering time increases dramatically, especially when I apply filters on the data. For example, I have a parent component that fetches a list of products and then displays them in categories. Each category further lists the products that belong to it. Hereโ€™s a simplified structure of my template: ```vue <template> <div> <div v-for="category in filteredCategories" :key="category.id"> <h2>{{ category.name }}</h2> <ul> <li v-for="product in filterProducts(category.products)" :key="product.id"> {{ product.name }} </li> </ul> </div> </div> </template> ``` The `filteredCategories` computed property filters categories based on user input, while the `filterProducts` method filters products per category. Hereโ€™s a snippet of what I've implemented for filtering: ```javascript computed: { filteredCategories() { return this.categories.filter(category => category.name.includes(this.searchTerm)); } }, methods: { filterProducts(products) { return products.filter(product => product.name.includes(this.productSearchTerm)); } } ``` However, I've been seeing a lot of unnecessary re-renders, and when I check the performance, I can see the component rendering taking more than 2 seconds for larger datasets, which is unacceptable. Iโ€™m also getting warnings in the console like `Vue warn]: Avoid mutating a prop directly` when I accidentally modify the `category.products` array directly in my filtering method. I tried using `v-bind:key` correctly, and Iโ€™ve also attempted using `v-once` for static parts but to no avail. How can I enhance the performance of my component in this scenario without running into the reactivity pitfalls? Any best practices would be greatly appreciated! For context: I'm using Javascript on Linux. I'm on CentOS using the latest version of Javascript. Any examples would be super helpful. This is part of a larger service I'm building.