Vue v-for
Directive
With normal JavaScript you might want to create HTML elements based on an array. You use a for-loop, and inside you need to create the elements, adjust them, and then add each element to your page. And these elements will not react to a change in the array.
With Vue you start with the HTML element you want to create into a list, with v-for
as an attribute, refer to the array inside the Vue instance, and let Vue take care of the rest. And the elements created with v-for
will automatically update when the array changes.
List Rendering
List rendering in Vue is done by using the v-for
directive, so that several HTML elements are created with a for-loop.
Below are three slightly different examples where v-for
is used.
Example
Display a list based on the items of an array.
<ol>
<li v-for="x in manyFoods">{{ x }}</li>
</ol>
Try it Yourself »
Loop Through an Array
Loop through an array to display different images:
Example
Show images of food, based on an array in the Vue instance.
<div>
<img v-for="x in manyFoods" v-bind:src="x">
</div>
Try it Yourself »
Loop Through Array of Objects
Loop through an array of objects and display the object properties:
Example
Show both images and names of different types of food, based on an array in the Vue instance.
<div>
<figure v-for="x in manyFoods">
<img v-bind:src="x.url">
<figcaption>{{ x.name }}</figcaption>
</figure>
</div>
Try it Yourself »
Get the index
The index number of an array element can be really useful in JavaScript for-loops. Luckily we can get the index number when using v-for
in Vue as well.
To get the index number with v-for
we need to give two comma separated words in parentheses: the first word will be the array element, and the second word will be the index of that array element.
Example
Show index number and food name of elements in the 'manyFoods' array in the Vue instance.
<p v-for="(x, index) in manyFoods">
{{ index }}: "{{ x }}" <br>
</p>
Try it Yourself »
We can also display both array element index and information from the array element itself, if the array elements are objects:
Example
Show both the array element index number, and text from the objects in the 'manyFoods' array.
<p v-for="(x, index) in manyFoods">
{{ index }}: "{{ x.name }}", url: "{{ x.url }}" <br>
</p>
Try it Yourself »