List Rendering (v-for & Key Tracking)
The v-for directive iterates over arrays or objects, rendering lists of elements. Providing a unique :key is critical for helping the Virtual DOM compile updates efficiently.
1 The Role of Key tracking
List rendering requires configuring specific keys:
- v-for syntax: Iterates through lists:
v-for="item in items"orv-for="(item, index) in items". - :key Attribute: A unique, stable identifier for each item. It helps Vue trace which elements have changed, were moved, or deleted, avoiding unnecessary DOM re-creation. Never use array indices as keys if the list order can change.
2 List Rendering in Templates
Let's check list iteration in action:
HTML — Vue List Rendering
<h4>Tasks Progress List:</h4>
<ul>
<!-- Always bind a unique :key to identify the item -->
<li v-for="(task, index) in tasks" :key="task.id">
<span>{{ index + 1 }}. {{ task.title }}</span>
<span v-if="task.isDone" class="success-badge">Done</span>
</li>
</ul>
<!-- Iterating through object properties -->
<div v-for="(val, name) in userMetadata" :key="name">
{{ name }}: {{ val }}
</div>
3 Code Challenge
Challenge: Write a component containing an array of book objects (each with an
id, title, and author). Render them in a list, displaying a "Remove" button next to each book that deletes it from the array when clicked.