Performance: v-for with v-if precedence
This affects rendering speed and responsiveness by controlling how many DOM nodes Vue creates and updates during list rendering.
<li v-for="item in filteredItems" :key="item.id">{{ item.name }}</li> <script setup> import { computed } from 'vue' const filteredItems = computed(() => items.filter(item => item.visible)) </script>
<li v-for="item in items" :key="item.id" v-if="item.visible">{{ item.name }}</li>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| v-for with v-if inside | Creates all nodes then removes some | N reflows for N items | High paint cost due to node removal | [X] Bad |
| v-for on pre-filtered list | Creates only needed nodes | Single reflow | Low paint cost | [OK] Good |
v-for and v-if on the same element, which happens first?v-for first to create the list of items.v-if filteringv-if decides which items to actually render.v-for runs first, then v-if filters the rendered items. -> Option Cv-for with v-if on the same element in Vue?v-for and v-if on the same element; v-for should come first logically but order in code doesn't affect behavior.<li v-for="item in items" v-if="item.active">{{ item.name }}</li> correctly places both directives on the <li> element with proper syntax.<ul>
<li v-for="item in items" v-if="item.show">{{ item.name }}</li>
</ul>items = [
{ name: 'A', show: true },
{ name: 'B', show: false },
{ name: 'C', show: true }
]show: true are rendered, so B is skipped.<div v-if="item.active" v-for="item in items">{{ item.name }}</div>items is an array of objects with active boolean property.v-for first, then v-if filters items, but this means all items are looped before filtering.v-if with v-for on the same element can cause unnecessary loops and slow rendering.v-for and v-if for performance?v-if inside v-for causes Vue to loop all items before filtering, which is inefficient for large lists.v-for loops only needed items without v-if.Pass the test and this pattern moves unknown