v-for
DirectiveWith 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 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.
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 to display different images:
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 an array of objects and display the object properties:
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 »
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.
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:
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 »
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!