Vue v-for Directive

Vue v-for Directive

The v-for directive is used to render a list of items based on an array.

It is one of the most frequently used directives in Vue.js applications.

Whenever your array data changes, Vue automatically updates the rendered list.


Basic v-for Syntax

The syntax for v-for requires a special format in the form of item in items.

Here, items is the source data array, and item is an alias for the array element being iterated on.

You place this directive directly on the HTML element you want to repeat.

Basic v-for Example:

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

Accessing the Index

You often need to know the index (position) of the current item in the array.

Vue allows you to provide a second alias for the index within the v-for directive.

The syntax becomes (item, index) in items.

v-for with Index Example:

<ol>
  <li v-for="(car, index) in cars">
    {{ index }} - {{ car }}
  </li>
</ol>

The Importance of the Key Attribute

When Vue updates a list rendered with v-for, it uses an "in-place patch" strategy by default.

To help Vue track each node's identity and reuse elements, you must provide a unique key attribute.

You bind the key using :key="uniqueValue".

This heavily improves performance and prevents rendering bugs during array updates.


Exercise 1 of 2

?

Which syntax is correct for iterating over an array named 'users' in Vue?

Exercise 2 of 2

?

Why is it highly recommended to provide a :key attribute when using v-for?