Vue School Logo

Browse 800+ Vue Lessons including the Vue 3 Masterclass

Learn More

How to Write Better Vue v-for Loops

Last Updated on Feb 25, 2020

In Vue, v-for loops are something that every project will use at some point or another. They allow you to write for loops in your template code and create elements iteratively.

v-for is most commonly used to render items in a list, but can also be used to iterate over an object's properties or even a set range.

When iterating over an array, Vue v-for loops look like this.

Foo.vue
<template>  <div v-for="product in products">    {{ product.name }}  </div></template>

In this article, we’ll be covering some ways to make your v-for loops more precise, predictable, and efficient.

Accessing index in v-for

In addition to accessing our values, we can also keep track of the index of each item.

To do this, we have to add an `index`` value after our item. It’s simple, and is useful for things like pagination, displaying the index of a list, showing rankings, etc.

Like other indices in programming, index starts at 0.

Preview

Add key to Vue v-for loops

A common Vue best practice is to use :key in your v-for loops.

key is a special attribute that lets us give hints for Vue's rendering system to identify specific virtual nodes.

If we don't provide a unique key, Vue will try to minimize element movement when updating the DOM.

For example, if we want to change the order of our list, instead of reordering the DOM elements - Vue will make edits to the elements in-place to reflect the data change. This is called an in-place patch.

Insert graphic of that

If we have a unique key reference for each element (usually some unique id), Vue's rendering system will reorder elements instead of performing in-place patches.

Use cases

Two cases where a missing key can cause problems in our v-for are when our v-for has:

  • components
  • stateful DOM elements (like form inputs)

Like we saw, Vue's default rendering avoids moving DOM elements, so if we had a child component or form input, it doesn't move with our product when we reorder our list. Instead, each product.name gets patched with the new product - but the input stays in place.

❌ Without key

The same thing applies if our iterated content contains a child component. Without a key, it will stay in place when we reorder our list.

❌ Without key