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.
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.
<figure v-for="x in manyFoods">
<img v-bind:src="x.url">
<figcaption>{{ x.name }}</figcaption>
</figure>
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>
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>
Try it Yourself »
Exercise:
List rendering in Vue can be done so that several HTML elements are created based on an array.
If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]
Report Error
If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted our
terms of use
,
cookie and privacy policy
.