Performance: v-for for list rendering
This affects how quickly the browser can render lists and update the DOM when data changes.
<template>
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
</template>
<script setup>
const items = Array.from({ length: 1000 }, (_, i) => ({ id: i, name: `Item ${i}` }));
</script><template>
<ul>
<li v-for="item in items">{{ item.name }}</li>
</ul>
</template>
<script setup>
const items = Array(1000).fill({ name: 'Item' });
</script>| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| v-for without key | Creates all nodes every update | Triggers reflow for every item | High paint cost due to full re-render | [X] Bad |
| v-for with unique key | Updates only changed nodes | Minimal reflows on update | Lower paint cost | [OK] Good |
| v-for with virtual scrolling | Creates only visible nodes | Very few reflows | Minimal paint cost | [OK] Good |
v-for directive do in Vue.js?v-forv-for directive is used to loop over arrays or objects and render elements multiple times.v-if control visibility, v-bind binds data, and v-on listens to events, so they do not repeat elements.v-for = repeat elements [OK]v-for in Vue?v-for syntaxv-for="item in items" where items is the array and item is the loop variable.<li v-for="item in items">{{ item }}</li> uses correct syntax and variable names. Options B, C, and D have incorrect order or variable names.v-for="item in items" [OK]<ul>
<li v-for="(fruit, index) in fruits" :key="index">{{ index }} - {{ fruit }}</li>
</ul>fruits: ['Apple', 'Banana', 'Cherry']
v-for uses (fruit, index) in fruits, so index is the position and fruit is the item.<ul>
<li v-for="item in items">{{ item }}</li>
</ul>items: null
v-for directive requires an array or object to loop over. If items is null, it is not iterable.null.const usersByCity = {
'New York': [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }],
'Paris': [{ id: 3, name: 'Claire' }]
}v-for to render a list showing city names and their users' names inside each city?usersByCity is an object where keys are city names and values are arrays of user objects.v-for to loop over object entriesv-for="(users, city) in usersByCity" to get city name and users array. Then loop over users array inside.<div v-for="(users, city) in usersByCity" :key="city">
<h3>{{ city }}</h3>
<ul>
<li v-for="user in users" :key="user.id">{{ user.name }}</li>
</ul>
</div> correctly uses (users, city) and nested v-for with keys. <div v-for="(city, users) in usersByCity" :key="city">
<h3>{{ city }}</h3>
<ul>
<li v-for="user in users" :key="user.id">{{ user.name }}</li>
</ul>
</div> swaps city and users order incorrectly. Options B and D misuse variables.Pass the test and this pattern moves unknown