loading

Vue v-for

You may want to use an array as the basis for HTML components when using standard JavaScript. You must construct the elements, make the necessary adjustments, and then add each element to your page using a for-loop. Furthermore, these components won’t respond when the array changes.

Using v-for as an attribute, you begin with the HTML element you wish to turn into a list with Vue. Then, you point to the array within the Vue instance and let Vue handle the rest. When the array changes, the items made with v-for will also update immediately.

List Rendering

The v-for directive is used in Vue to render lists, creating multiple HTML components with a for-loop.

Here are three quite different instances of v-for usage.

Example

Show a list based on an array’s items.

				
					<ol>
  <li v-for="x in manyFoods">{{ x }}</li>
</ol>
				
			

Loop Through an Array

Iterate over an array to show various images:

Example

Display food photos by using an array in the Vue instance.

				
					<div>
  <img v-for="x in manyFoods" v-bind:src="x">
</div>
				
			

Loop Through Array of Objects

Display the characteristics of each object by iterating through an array of them:

Example

Display the names and photos of various food varieties based on an array within the Vue instance.

				
					<div>
  <figure v-for="x in manyFoods">
    <img v-bind:src="x.url">
    <figcaption>{{ x.name }}</figcaption>
  </figure>
</div>
				
			

Get the index

In JavaScript for-loops, the index number of an array entry can be quite helpful. Luckily, utilizing v-for in Vue also allows us to obtain the index number.

Two words, separated by commas and enclosed in parentheses, are required to obtain the index number with v-for: the array element (first word) and its index (second word).

Example

Display the element names and index numbers in the ‘manyFoods’ array in the Vue instance.

				
					<p v-for="(x, index) in manyFoods">
  {{ index }}: "{{ x }}" <br>
</p>
				
			

If the array elements are objects, we can also display the information from the array element itself as well as the array element index:

Example

Present the text from the items in the “manyFoods” array in addition to the array element index number.

				
					<p v-for="(x, index) in manyFoods">
  {{ index }}: "{{ x.name }}", url: "{{ x.url }}" <br>
</p>
				
			
Share this Doc

Vue v-for

Or copy link

Explore Topic