Using v-for in Vue.js to Iterate Over a List
<div id="app">
<ul>
<li v-for="item in items" :key="item.id">
{{ item.name }}
</li>
</ul>
</div>
new Vue({
el: '#app',
data: {
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' }
]
}
})
- In the Vue template, a
div
element with the id
of "app" is defined to contain the Vue app. - Inside the
div
, an ul
element is used to create an unordered list. - The
li
element contains a v-for
directive, which iterates over the items
array in the Vue instance. - The
:key
attribute is used to provide a unique identifier for each item in the list. - Within the
li
element, the item.name
is displayed using double curly braces {{ }}
. - In the Vue instance, a new Vue instance is created with the
el
property set to the ID of the containing div
element. - The
data
property defines an items
array, with each item containing an id
and a name
. - When the Vue app is mounted, the
v-for
directive will iterate over the items
array and render the list of items in the unordered list.