In Vue, the v-for directive is used to render a list of items based on an array or an object.
It iterates over each item in the array or each key-value pair in the object and generates a corresponding DOM element for each item.
"items" is an array of objects, and "item" is an alias representing each "item" in the array.
For each "item" in the "items" array, a
The ":key" attribute is used to provide a unique key for each rendered element, which helps Vue.js efficiently update the DOM when the array changes.
<ul> <li v-for="city in cities" :key="city.id"> {{ city.name }} </li> </ul>
v-for="city in cities": This syntax creates a loop where "city" represents the current "city obj" being iterated over, and "cities" is the array being looped through.
:key="city.id": It's important to provide a unique key for each item to help Vue efficiently update the DOM when the list changes.
We can also access the "index" of each "city" by specifying (city, index) in the v-for directive.
<ul> <li v-for="(city, index) in cities" :key="index"> {{ index + 1 }}. {{ city.name }} </li> </ul>
Here, "index" represents the "index" of the current "city" in the array.
<ul> <li v-for="(value, key) in object" :key="key"> {{ key }}: {{ value }} </li> </ul>
we can iterate over the properties of an object, we can use (value, key) in the "v-for" directive.
Here, "key" represents the property "name", and "value" represents the property value.
<p v-for="currentNum in 20" :key="currentNum"> Current Item No: {{ currentNum }} </p>
We can also use v-for to iterate over a range of numbers by specifying a range instead of an array or object.
<ul> <li v-for="user in users" :key="user.id" v-if="user.isActive">{{ user.name }}</li> </ul>
"currentNum" represents each number from 1 to 20, and a
element is rendered for each number.
The above code will render with the text `Current Item No: ` along with numbers 1 to 20.
We can combine v-for with v-if for conditional rendering within the loop.
Only `users` with `isActive` set to true will be rendered.
The v-for directive provides a powerful way to render lists of items dynamically in Vue.js templates.
It is commonly used in conjunction with arrays or objects stored in Vue data properties to render dynamic content in the UI.