Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 87 ยท Template Syntax

List Rendering with v-for

Render arrays, objects and number ranges with v-for in Vue 3. Learn why key matters, how to use template with v-for, and how to avoid the v-if with v-for trap.

Most data comes in lists: products, messages, search results, table rows. Writing one element per item by hand is impossible, and building them with JavaScript string concatenation is error-prone. Vue's v-for directive repeats an element once for every item in a collection, and keeps the page in step as the collection changes.

This lesson covers looping over arrays, objects and ranges, the key attribute (the single most misunderstood part of v-for), grouping with <template>, and the traps of combining v-for with v-if.

Looping over an array

The syntax is item in items, where items is your array and item is the variable for the current element. You can also ask for the index with (item, index) in items:

Rendering an array with an index

Each press of the button pushes an object onto the array, and a new <li> appears. Vue detects push, splice, sort and every other change to a reactive array (see Reactive State with ref). You can write of instead of in if you prefer JavaScript's for...of spelling.

Inside the loop you have access to everything from the parent scope too, so {{ prefix }} {{ fruit.name }} works.

Looping over an object

v-for can iterate an object's properties. You receive the value first, then the key, then the index:

Iterating over an object

The order follows Object.keys(), which is the insertion order for ordinary string keys.

Looping over a range

If the source is an integer n, Vue repeats the element n times, counting from 1:

HTML
<span v-for="n in 5" :key="n">{{ n }} </span>

This renders 1 2 3 4 5. It is a quick way to draw stars in a rating, page numbers or a grid, with no array required. Strings and any iterable (a Set, a Map) also work.

Why key matters

When the list changes, Vue must decide which existing DOM element corresponds to which item. Without a hint it uses an "in-place patch" strategy: it reuses the elements in order and updates their content to match the new data. That is fast and fine for simple output, but wrong when the elements carry state of their own: a typed value in an input, a focus, an animation, a child component's data.

The key attribute is the hint. Give each item a unique, stable identifier (an id from your database, never the array index) and Vue can move, add and remove the right elements:

Why keys keep state attached to the right row

Type a word next to each label in both columns, then press the button. In the left column the labels flip but the words you typed stay in the same positions: Vue patched each row in place because index keys said "the first row is still the first row". In the right column the inputs travel with their labels, because the keys identify the rows.

flowchart LR
  subgraph Index["key = index"]
    direction TB
    I0["0: Alpha"] --- I1["1: Beta"] --- I2["2: Gamma"]
  end
  subgraph Id["key = id"]
    direction TB
    A["a: Alpha"] --- B["b: Beta"] --- C["c: Gamma"]
  end
  Index -- "reverse" --> R1["Same DOM rows patched in place;<br/>typed text stays at its position"]
  Id -- "reverse" --> R2["DOM rows are moved;<br/>typed text follows its item"]

Keys tell Vue which DOM row belongs to which item, so reordering moves rows instead of rewriting them.

Rules for keys:

  • Use primitives (strings or numbers). Do not use objects as keys.
  • Keys must be unique among siblings in the same loop.
  • Put the key on the element that has v-for. When v-for is on a <template>, the key goes on the <template> tag.
  • Using the index is acceptable only for static lists that are never reordered, filtered or inserted into.

v-for on a <template>

To repeat several sibling elements per item without a wrapper, put v-for on a <template>, just as you did for v-if in Conditional Rendering. The object example above already did this with <dt> and <dd>.

Showing a filtered or sorted list

Do not mutate your data just to display it differently. Compute a new array and loop over that, using a computed property for anything beyond a one-liner:

Filtering with a computed list

Note the separate v-if for the empty message, outside the loop. That is the recommended place for it.

v-if together with v-for

Putting both on the same element is a trap. In Vue 3, v-if has a higher priority than v-for, so the condition is evaluated first and cannot see the loop variable:

HTML
<!-- Broken: "todo" does not exist yet when v-if runs -->
<li v-for="todo in todos" v-if="!todo.done">{{ todo.text }}</li>

This produces a warning and an error about the property todo. (Vue 2 did the opposite, so old tutorials teach a different rule.) There are two clean fixes. If you only want to skip some items, filter in a computed list as above. If you need to switch each item's rendering, move the v-for to a <template> and put v-if on the inner element:

HTML
<template v-for="todo in todos" :key="todo.id">
  <li v-if="!todo.done">{{ todo.text }}</li>
</template>

Arrays and reactivity details

  • Mutating methods (push, pop, shift, unshift, splice, sort, reverse) update the view.
  • Non-mutating methods (filter, map, slice, concat) return a new array: assign it back (list.value = list.value.filter(...)) or use it in a computed.
  • A ref wraps the array, so use .value in script and no .value in the template.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does v-for="n in 3" render?

    When the source is a whole number, Vue repeats the element that many times and n counts from 1.
  2. 2. What is a good value for :key in a list of database records?

    Keys must be unique, stable primitives. A record id identifies the same item across reordering. A random key would recreate every row on each render.
  3. 3. In Vue 3, what happens with <li v-for="t in todos" v-if="!t.done">?

    v-if has a higher priority than v-for in Vue 3. Filter with a computed property, or move v-for to a template wrapper.
  4. 4. For (value, key, index) in obj, which order does Vue pass the arguments in?

    The value comes first, then the property name, then the numeric position.
  5. 5. Where does the key go when v-for is on a template tag?

    Put :key on the template element that carries v-for.

Summary

  • v-for="item in items" repeats an element for each array item; add (item, index) for the position.
  • Objects give (value, key, index); an integer n gives 1..n; any iterable works.
  • Always give list items a unique, stable :key so Vue can move rows instead of patching them in place; avoid the index when the list can change order.
  • Use <template v-for> to repeat several elements without a wrapper.
  • Filter and sort with computed lists instead of v-if on the same element as v-for.

Next, react to clicks and keystrokes in Handling Events.