List rendering with v-for
Rendering arrays, objects and ranges with v-for, why every list item needs a stable key, and how to filter and sort lists without mixing v-if into the loop.
Text interpolation and attribute bindingConditional rendering with v-if and v-show
List rendering with v-for
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- `v-for="item in items"` renders its element once per item, and the loop variable is visible to that element and everything inside it. `(item, index)` adds the position, and `of` works as a synonym for `in`.
- `v-for` also iterates objects as `(value, key, index)`, integer ranges as `n in 10` starting at 1, and any iterable such as a `Map` or `Set`.
- Without a `key`, Vue patches list items in place by position, which is fast but leaves stateful items (inputs, child components) attached to the wrong data after a reorder. A unique, stable `:key` such as a database id lets Vue move items instead.
- Array indexes make poor keys for lists that can be reordered, filtered or prepended to, because the index of a given item changes when the list does.
- To filter or sort, loop over a computed list rather than putting `v-if` on the same element as `v-for`; to hide the whole list, put `v-if` on a wrapper.
- `sort()` and `reverse()` mutate their array. Inside a computed property, use `toSorted()` or copy first, so the source list is not changed by rendering it.
Templates need loops
Most data arrives as collections: products in a cart, messages in a thread, rows in a table. Writing one element per item by hand is obviously impossible when the number of items is only known at runtime. You need the template to say “repeat this element for each thing in this list”, and to keep the rendered list in step as items are added, removed or reordered. That is what v-for does.
The basic loop
<script setup>
import { ref } from 'vue'
const items = ref([
{ id: 1, label: '10 party hats', purchased: false },
{ id: 2, label: '2 board games', purchased: true },
{ id: 3, label: '20 cups', purchased: false },
])
</script>
<template>
<ul>
<li v-for="item in items" :key="item.id">
{{ item.label }}
</li>
</ul>
</template>
The syntax mirrors a JavaScript for...of loop. item is a new variable that exists only inside the element carrying v-for and its children. You can write of instead of in; they mean the same thing.
A second variable gives you the position, and the item can be destructured just like a function parameter:
<li v-for="(item, index) in items" :key="item.id">
{{ index + 1 }}. {{ item.label }}
</li>
<li v-for="({ id, label }, index) in items" :key="id">
{{ index + 1 }}. {{ label }}
</li>
Destructuring itself is a JavaScript feature; destructuring and spread covers it.
Objects, ranges and other iterables
v-for is not limited to arrays. Over a plain object, it yields the value, then the key, then the index, in the same order as Object.keys():
<dl>
<template v-for="(value, key) in specs" :key="key">
<dt>{{ key }}</dt>
<dd>{{ value }}</dd>
</template>
</dl>
Given an integer, it counts from 1 up to that number, which is handy for star ratings or placeholder skeletons:
<span v-for="n in 5" :key="n">★</span>
It also accepts any iterable, including Map and Set.
The <dl> example shows the <template> trick from the previous lesson applied to loops: <template v-for> repeats a group of sibling elements without a wrapper. In Vue 3 the key goes on the <template> tag itself.
What the key is for
When the list changes, Vue has to update the DOM to match. By default it uses an in-place strategy: it walks the list by position and patches row 0 with item 0’s new data, row 1 with item 1’s, and so on. That is cheap, and for a list of plain text it is perfectly correct.
It breaks when rows hold state that is not driven by the data. Picture a shelf of labelled jars where each jar also holds whatever someone put in it. If you reorder the labels but leave the jars where they are, every jar now has a new label and the wrong contents. Rows in a list are jars: a half-typed <input>, a focused button, a child component with its own local state. Patch by position after inserting an item at the top, and every one of those bits of state ends up next to the wrong item.
A key gives each row an identity. With :key="item.id", Vue matches old and new rows by key, moves the existing DOM nodes into their new order, creates nodes only for new keys, and removes nodes whose keys disappeared. The jars move with their labels.
Keys should be:
- Unique among siblings. Duplicate keys produce a warning and unpredictable updates.
- Stable. The same item gets the same key on every render. A database id or a slug is ideal.
Math.random()is the worst choice, because every render looks like an entirely new list. - Primitive. Strings, numbers or symbols, not objects.
Array indexes are stable only if the list never reorders, filters or has items inserted anywhere but the end. When in doubt, use a real id. The Vue style guide treats a key on every v-for as essential, and the official ESLint plugin flags a missing one.
React draws the same lesson from the same diffing problem; rendering lists and keys is its version, and how Vue reactivity works goes deeper into what Vue does on a re-render.
Filtering and sorting
The natural impulse is to put v-if on the looping element. In Vue 3 that fails, because v-if runs first and cannot see the loop variable. The idiomatic fix is to loop over a derived list:
<script setup>
import { ref, computed } from 'vue'
const items = ref([/* ... */])
const hidePurchased = ref(false)
const visibleItems = computed(() =>
hidePurchased.value
? items.value.filter((item) => !item.purchased)
: items.value
)
const byLabel = computed(() =>
visibleItems.value.toSorted((a, b) => a.label.localeCompare(b.label))
)
</script>
<template>
<ul v-if="items.length">
<li v-for="item in byLabel" :key="item.id">{{ item.label }}</li>
</ul>
<p v-else>Nothing on the list yet.</p>
</template>
Two details matter. computed caches its result and recalculates only when items or hidePurchased changes, which is better than filtering inside the template on every render; computed properties covers it properly. And toSorted() returns a new array, whereas sort() and reverse() reorder the original in place. Mutating reactive state from inside a computed property is a bug, so copy before you sort. Arrays and array methods lists which methods mutate.
Notice the v-if on the <ul>: to hide the whole list, the condition goes on a wrapper, where it applies once instead of per item.
Changing the list
Because items is reactive, the rendered list follows the array. items.value.push(newItem), splice, assigning a whole new filtered array, or setting items.value[0] = x all trigger an update. Vue 3 tracks arrays through JavaScript proxies, so even index assignment works, which was not true in Vue 2. Why that is so is the subject of the next group, starting with ref and reactive.
What the video covers
The embed is a seven-minute stretch of Vue School’s Vue Fundamentals with the Composition API course, from May 2024. It has three back-to-back chapters: rendering a list with v-for, why and how to add keys, and further v-for usage. The course uses a setup() function in a browser build for most of its length rather than <script setup>; the template syntax is identical either way. The clip does not cover the v-if precedence rule, <template v-for>, or sorting without mutation, which this lesson adds. LearnVue’s two short videos linked below are good follow-ups on keys and on common v-for patterns.
Where this fits
Lists usually render components rather than bare <li> elements, passing each item down as props. That is where the next group picks up, in components and props. Animating items as they enter, leave and move is handled by TransitionGroup.
Check yourself
A list of todos is rendered with `v-for` and `:key="index"`, and each row has a checkbox and a text input. A new todo is inserted at the top. What goes wrong?
Every existing todo's index shifts by one, so each key now points at a different todo. Vue reuses the DOM row that had key 0 for the new todo, the row that had key 1 for what used to be todo 0, and so on. Any DOM state that is not bound to data, like a half-typed input or focus, stays on the old row and appears next to the wrong todo. Using each todo's unique id as the key fixes it.
What does `<span v-for="n in 3">{{ n }}</span>` render?
Three spans containing 1, 2 and 3. An integer range in `v-for` starts at 1, not 0.
How do you render only the active users from `users` without putting `v-if` on the `v-for` element?
Create a computed property such as `const activeUsers = computed(() => users.value.filter(u => u.active))` and loop over `activeUsers`. Alternatively, put `v-for` on a `<template>` and `v-if` on the element inside it, though the computed version is clearer and only filters when `users` changes.
When a `v-for` sits on a `<template>` element in Vue 3, where does the `key` go?
On the `<template>` itself. Vue 3 expects the key on the `<template v-for>` element rather than on its children.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.