Consider this Vue template snippet:
<ul>
<li v-for="item in items" v-if="item.show" :key="item.id">{{ item.name }}</li>
</ul>Given items = [{ id: 1, name: 'A', show: true }, { id: 2, name: 'B', show: false }, { id: 3, name: 'C', show: true }], what will be rendered?
<ul> <li v-for="item in items" v-if="item.show" :key="item.id">{{ item.name }}</li> </ul>
Remember that v-if on the same element as v-for filters items after the loop runs.
The v-for loops over all items, but v-if on the same element only renders those where item.show is true. So only items with show: true appear.
You want to render a list but only show items that meet a condition. Which approach is better for performance?
Think about how many times Vue has to evaluate the condition.
Filtering the array before rendering means Vue only loops over needed items, improving performance. Using v-if inside v-for runs the condition for every item.
Which option contains a syntax error in Vue template using v-for and v-if?
Check if all directives have valid expressions.
Option D uses v-if without a condition, which is invalid syntax and causes a compile error.
Given this template:
<ul>
<li v-for="item in items" v-if="item.visible" :key="item.id">{{ item.text }}</li>
</ul>And data:
items = [{ id: 1, text: 'One', visible: false }, { id: 2, text: 'Two', visible: false }]Why does nothing render?
<ul> <li v-for="item in items" v-if="item.visible" :key="item.id">{{ item.text }}</li> </ul>
Check the values of the visible property in the data.
All items have visible: false, so v-if prevents rendering any list item.
Consider this Vue template:
<ul>
<li v-for="group in groups" :key="group.id">
<h3>{{ group.name }}</h3>
<ul>
<li v-for="item in group.items" v-if="item.active" :key="item.id">{{ item.label }}</li>
</ul>
</li>
</ul>Given data:
groups = [
{ id: 1, name: 'Group 1', items: [
{ id: 'a', label: 'Item A', active: true },
{ id: 'b', label: 'Item B', active: false }
]},
{ id: 2, name: 'Group 2', items: [
{ id: 'c', label: 'Item C', active: false },
{ id: 'd', label: 'Item D', active: true }
]}
]What will be the rendered HTML?
<ul> <li v-for="group in groups" :key="group.id"> <h3>{{ group.name }}</h3> <ul> <li v-for="item in group.items" v-if="item.active" :key="item.id">{{ item.label }}</li> </ul> </li> </ul>
Remember v-if filters items inside each group's items array.
Only items with active: true render inside each group's list. Group 1 shows Item A, Group 2 shows Item D.