Vue — Lists
Basic v-for
<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: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Cherry' }
]
}
}
}
</script>
With index
<div v-for="(item, index) in items" :key="item.id">
{{ index }}. {{ item.name }}
</div>
Object iteration
<div v-for="(value, key) in user" :key="key">
{{ key }}: {{ value }}
</div>
Number iteration
<span v-for="n in 5" :key="n">{{ n }} </span>
<!-- Output: 1 2 3 4 5 -->
Key attribute
<!-- Always use key for efficiency -->
<li v-for="item in items" :key="item.id">
{{ item.name }}
</li>
<!-- Avoid using index as key -->
<li v-for="(item, index) in items" :key="index">
{{ item.name }}
</li>
Nested lists
<div v-for="category in categories" :key="category.id">
<h3>{{ category.name }}</h3>
<ul>
<li v-for="item in category.items" :key="item.id">
{{ item.name }}
</li>
</ul>
</div>
v-for with v-if
<!-- Not recommended together -->
<li v-for="item in items" v-if="item.active" :key="item.id">
{{ item.name }}
</li>
<!-- Better: use computed -->
<li v-for="item in activeItems" :key="item.id">
{{ item.name }}
</li>
Component v-for
<my-component
v-for="item in items"
:key="item.id"
:item="item"
></my-component>
Mini Practice
- Render a list of items
- Add index to iteration
- Iterate over object properties
- Use keys for performance
Up Next
Continue with Methods - Event handling.
Related Topics
Frequently Asked Questions about Lists
What is Lists in Vue?
Lists is a fundamental concept in Vue. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Lists?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Lists.
Why is Lists important in Vue?
Lists is essential for Vue development. Understanding this concept will help you write better code and solve real-world problems more effectively.