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.
- {{ x }}
Loop Through an Array
Iterate over an array to show various images:
Example
Display food photos by using an array in the Vue instance.
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.
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.
{{ index }}: "{{ x }}"
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.
{{ index }}: "{{ x.name }}", url: "{{ x.url }}"