How to do list rendering (looping) using v-for in Vue.js

in Code Write a comment

Learn the basics of list rending in Vue.js by looping through an array of items.

Rendering an array of items in Vue.js

In Vue.js you can use a v-for directive to loop through an array of items, using the following syntax item in items.

<ul>
  <li v-for="todo in todos">
    {{ todo.title }}
  </li>
</ul>

In the example above todos is an array (or a source of data) and todo is a name of the array element being iterated on (you can rename it as you like).

data: {
  todos: [
    { text: "Subscibe to Renatello.com newsletter", done: true },
    { text: "Learn Vue", done: false },
    { text: "Build awesome projects", done: false }
  ]
}

This will render to:

Subscibe to Renatello.com newsletter
Learn Vue
Build awesome projects

Note that todo item inside the v-for block can render all its properties, e.g. todo.text and todo.done.


Hi, I'm Renat 👋

âžœ  


v-for index of the current item

In Vue.js you can also add a second, optional argument to the v-for. It will show the index of the current item in the array.

<ul>
  <li v-for="(todo, index) in todos">
    {{ index }}. {{ todo.title }}
  </li>
</ul>

It will render to:

0. Subscibe to Renatello.com newsletter
1. Learn Vue
2. Build awesome projects

v-for unique keys

Vue.js v-for directive requires a unique key attribute for each item to be provided.

It will allow Vue.js to reuse and reorder existing elements. You should always provide the unique key attribute, unless your list is very simple.

<ul>
  <li v-for="(todo, index) in todos" :key="todo:id">
    {{ index }}. {{ todo.title }}
  </li>
</ul>

Note the :key attribute.

data: {
  todos: [
    { id: 1, text: "Subscibe to Renatello.com newsletter", done: true },
    { id: 2, text: "Learn Vue", done: false },
    { id: 3, text: "Build awesome projects", done: false }
  ]
}

If you find this post useful, please let me know in the comments below. 
Cheers,
Renat Galyamov

Want to share this with your friends?
👉renatello.com/vue-js-v-for-loop

PS: Make sure you check other Vue.js tutorials, e.g. building an infinite scroll in Vue.js (Vuex + API).

Incoming search terms:

A collection of UI components for
Bootstrap 4/5 and Vue.js

Get now

Write a Comment

Comment