Skip to main content

How does v-for work?

v-for is a Vue directive used to render lists: arrays, objects, numbers, and even the results of iterators.

In simpler terms:

v-for repeats a template for each item in a collection.


Basic syntax

html
<li v-for="item in items">{{ item }}</li>
js
data() { return { items: ['A', 'B', 'C'] } }

The result is three <li> elements.


Iterator variables: item, index

html
<li v-for="(item, index) in items"> {{ index }} - {{ item }} </li>

The required key attribute

Vue requires you to specify :key for correct item tracking:

html
<li v-for="user in users" :key="user.id"> {{ user.name }} </li>

Why?

  • improves performance
  • helps the DOM update correctly
  • prevents bugs when items are reordered

Iterating over an object

html
<div v-for="(value, key, index) in user" :key="key"> {{ key }}: {{ value }} </div>

The order is: (value, key, index).


Iterating over a number

html
<div v-for="n in 5">{{ n }}</div>

This outputs the digits 1-5.


v-for inside template

For grouping:

html
<template v-for="item in list" :key="item.id"> <h3>{{ item.title }}</h3> <p>{{ item.text }}</p> </template>

<template> itself is not rendered in the DOM.


Combining with v-if

You cannot put both on the same element (Vue 3):

html
<li v-for="item in items" v-if="item.visible">Not allowed</li>

But you can through <template>:

html
<template v-for="item in items" :key="item.id"> <li v-if="item.visible">{{ item.name }}</li> </template>

Or, better, filter beforehand:

js
visibleItems() { return this.items.filter(i => i.visible) }

Tuples (array of arrays)

html
<div v-for="([key, value]) in Object.entries(obj)" :key="key"> {{ key }}: {{ value }} </div>

v-for with components

You can pass the item as props:

html
<UserCard v-for="user in users" :key="user.id" :user="user" />

How v-for works "under the hood"

Vue does the following:

  1. Iterates over the collection
  2. Creates virtual DOM nodes for each item
  3. Matches them by their keys (key)
  4. Optimally updates the real DOM nodes when the data changes

Without key, Vue uses in-place patching, which can behave unexpectedly.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.