To iterate over an array using v-for
directive in Vue.js, you can follow these steps:
data
section.v-for
directive in your template to loop over the array.Here's an example:
<template>
<div>
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' }
]
};
}
};
</script>
In this example, the items
array is being iterated using v-for
. Each item in the array is assigned to the variable item
, and its id
is used as the key
to ensure Vue efficiently updates the element when the array changes. The name
property is then rendered in each <li>
element.
You can also access the index of each item by using the (item, index) in items
syntax. For example:
<li v-for="(item, index) in items" :key="item.id">{{ index }} - {{ item.name }}</li>
This will display the index followed by the item's name in each <li>
element.