Concept Flow - v-for with v-if precedence
Start v-for loop
For each item
Evaluate v-if condition
Render item
Next item or End loop
The v-for loop runs first, then for each item, the v-if condition is checked. Items passing v-if render; others skip.
<template>
<ul>
<li v-for="item in items" v-if="item.show" :key="item.id">{{ item.name }}</li>
</ul>
</template>| Step | Current item | v-if condition (item.show) | Render? | Output |
|---|---|---|---|---|
| 1 | {id:1, name:'Apple', show:true} | true | Yes | <li>Apple</li> |
| 2 | {id:2, name:'Banana', show:false} | false | No | |
| 3 | {id:3, name:'Cherry', show:true} | true | Yes | <li>Cherry</li> |
| 4 | End of items | - | - | Loop ends |
| Variable | Start | After 1 | After 2 | After 3 | Final |
|---|---|---|---|---|---|
| item | undefined | {id:1, name:'Apple', show:true} | {id:2, name:'Banana', show:false} | {id:3, name:'Cherry', show:true} | undefined |
| renderedItems | [] | [Apple] | [Apple] | [Apple, Cherry] | [Apple, Cherry] |
v-for loops over all items first. v-if runs on each item after v-for picks it. Only items passing v-if render. Use v-if inside v-for to conditionally render. Remember: v-for has higher precedence than v-if.
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