Performance: v-for with objects
This affects rendering speed and DOM update performance when looping over object properties in Vue templates.
<template>
<ul>
<li v-for="(value, key) in items" :key="key">
{{ key }}: {{ value }}
</li>
</ul>
</template><template>
<ul>
<li v-for="(value, key) in items" :key="Math.random()">
{{ key }}: {{ value }}
</li>
</ul>
</template>| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| v-for with random keys | Full node replacement on each update | Triggers full reflow per update | High paint cost due to many node changes | [X] Bad |
| v-for with stable keys (object keys) | Only changed nodes updated | Minimal reflows limited to changed items | Lower paint cost with fewer DOM changes | [OK] Good |
v-for to loop over an object, which syntax correctly accesses the key and value?v-for loops over objects using (value, key) syntax, where the first variable is the value and the second is the key.v-for="(value, key) in object" uses (value, key) in object, which is the correct order and syntax.v-for?key as the unique identifier is correct.:key="key" uses :key="key", which is correct. :key="value.id" assumes value has an id, which may not exist. :key="index" uses index which is less stable. :key="object" uses the whole object, which is invalid.<ul>
<li v-for="(value, key) in userInfo" :key="key">{{ key }}: {{ value }}</li>
</ul>userInfo: { name: 'Anna', age: 30 }name: 'Anna' and age: 30, the list items show "name: Anna" and "age: 30".<div v-for="(key, value) in settings" :key="key">
{{ key }}: {{ value }}
</div>(value, key) order when looping over objects, but here it is reversed as (key, value).const data = { a: 0, b: '', c: null, d: 'Hello' }v-for to display only keys with truthy values?v-if="value" inside the loop filters out falsy values like 0, '', and null.<div v-for="(value, key) in data" :key="key">{{ key }}: {{ value }}</div> shows all values including falsy. <div v-for="(value, key) in Object.entries(data)" :key="key">{{ key }}: {{ value }}</div> uses Object.entries but does not filter. <div v-for="(value, key) in data" v-show="value" :key="key">{{ key }}: {{ value }}</div> uses v-show which hides but still renders elements.Pass the test and this pattern moves unknown