TExcelTAD
Home › Vue › Vue v-for

Vue v-for

v-for renders an element once for every item in a list. Its syntax reads like a JavaScript for…of loop: item in items, where items is the source data and item is a name you choose for the current element.

html
<li v-for="fruit in fruits">{{ fruit }}</li>

Looping over an array

html · try it yourself
<div id="app">
  <h3>Shopping list ({{ items.length }})</h3>
  <ol>
    <li v-for="(item, index) in items" :key="item">
      {{ item }} <button @click="items.splice(index, 1)">✕</button>
    </li>
  </ol>
  <input v-model="next" @keyup.enter="add" placeholder="Add item + Enter">
</div>

<script type="module">
  import { createApp } from 'vue';

  createApp({
    data: () => ({ items: ['Bread', 'Milk', 'Eggs'], next: '' }),
    methods: {
      add() {
        if (this.next && !this.items.includes(this.next)) this.items.push(this.next);
        this.next = '';
      }
    }
  }).mount('#app');
</script>

The optional second variable, index, is the position of the item (starting at 0). Vue watches array methods such as push, splice, sort and reverse and updates the list automatically.

The key attribute

Give each repeated element a unique :key. Vue uses keys to recognise which element belongs to which item, so it can move, add and remove DOM elements correctly instead of re-using the wrong ones.

Good keys Bad keys
A database id: :key="user.id" The index when the list can be reordered or filtered
A unique string: :key="product.sku" An object: :key="user"
A value that can repeat

Tip: Always use :key with v-for. It is required on components in a loop and on <template v-for>'s children positions, and it prevents subtle bugs where input text or component state "jumps" to the wrong row.

Looping over objects

When the source is an object, you get the value, then the key, then the index:

html · try it yourself
<div id="app">
  <table border="1" cellpadding="6">
    <tr v-for="(value, key, i) in book" :key="key">
      <td>{{ i + 1 }}</td>
      <th>{{ key }}</th>
      <td>{{ value }}</td>
    </tr>
  </table>
</div>

<script type="module">
  import { createApp } from 'vue';

  createApp({
    data: () => ({
      book: { title: 'The Little Prince', author: 'Antoine de Saint-Exupéry', year: 1943, pages: 96 }
    })
  }).mount('#app');
</script>

Looping over a range

v-for="n in 5" repeats 5 times with n going from 1 to 5 (not 0!).

html · try it yourself
<style> .star { font-size: 28px; cursor: pointer; } </style>

<div id="app">
  <span v-for="n in 5" :key="n" class="star" @click="rating = n">
    {{ n <= rating ? '★' : '☆' }}
  </span>
  <p>Your rating: {{ rating }} / 5</p>
</div>

<script type="module">
  import { createApp } from 'vue';
  createApp({ data: () => ({ rating: 3 }) }).mount('#app');
</script>

Lists of objects and destructuring

Real lists usually hold objects. You can destructure the item directly in the v-for expression:

html · try it yourself
<style> .low { color: #b91c1c; } </style>

<div id="app">
  <ul>
    <li v-for="{ id, name, stock } in products" :key="id" :class="{ low: stock < 5 }">
      #{{ id }} {{ name }} — {{ stock }} in stock
    </li>
  </ul>
  <button @click="products.sort((a, b) => a.stock - b.stock)">Sort by stock</button>
  <button @click="products.reverse()">Reverse</button>
</div>

<script type="module">
  import { createApp } from 'vue';

  createApp({
    data: () => ({
      products: [
        { id: 1, name: 'Espresso Beans', stock: 12 },
        { id: 2, name: 'Green Tea', stock: 3 },
        { id: 3, name: 'Oat Milk', stock: 25 },
        { id: 4, name: 'Dark Chocolate', stock: 1 }
      ]
    })
  }).mount('#app');
</script>

Repeating a group with <template>

To repeat more than one element per item without a wrapper, use <template v-for>:

html
<dl>
  <template v-for="term in glossary" :key="term.word">
    <dt>{{ term.word }}</dt>
    <dd>{{ term.meaning }}</dd>
  </template>
</dl>

Filtering and sorting

Don't mutate your data just to display it differently. Create a computed property that returns a filtered or sorted copy, and loop over that (you will learn computed properties soon):

js
computed: {
  inStock() {
    return this.products.filter(p => p.stock > 0);
  }
}

Note: Remember from the v-if lesson: never put v-if and v-for on the same element. Filter with a computed property, or move v-if to an inner element.

Test yourself

Why should you add :key to elements rendered with v-for?

  1. To style each element
  2. So Vue can track which element belongs to which item
  3. To make the loop run faster in JavaScript
  4. Keys are only needed for objects

What values does n take in v-for="n in 3"?

  1. 0, 1, 2
  2. 1, 2, 3
  3. 0, 1, 2, 3
  4. 3 only

When looping over an object with v-for="(a, b, c) in obj", what is b?

  1. The value
  2. The index
  3. The property key
  4. The whole object