vue实现列表展示
Vue 实现列表展示
在 Vue 中实现列表展示通常使用 v-for 指令,结合数据绑定和动态渲染功能。以下是几种常见的实现方式:
基础列表渲染
使用 v-for 指令遍历数组,动态生成列表项。假设有一个数据数组 items:
<template>
<ul>
<li v-for="item in items" :key="item.id">
{{ item.name }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' }
]
}
}
}
</script>
带索引的列表渲染
如果需要获取当前项的索引,可以在 v-for 中添加第二个参数:
<template>
<ul>
<li v-for="(item, index) in items" :key="item.id">
{{ index + 1 }}. {{ item.name }}
</li>
</ul>
</template>
对象列表渲染
v-for 也可以遍历对象的属性,生成键值对列表:
<template>
<ul>
<li v-for="(value, key) in object" :key="key">
{{ key }}: {{ value }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
object: {
name: 'Vue',
version: '3.x',
language: 'JavaScript'
}
}
}
}
</script>
动态样式绑定
为列表项添加动态样式,可以通过 :class 或 :style 绑定:
<template>
<ul>
<li
v-for="item in items"
:key="item.id"
:class="{ 'active': item.isActive }"
@click="toggleActive(item)"
>
{{ item.name }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: 'Item 1', isActive: false },
{ id: 2, name: 'Item 2', isActive: false }
]
}
},
methods: {
toggleActive(item) {
item.isActive = !item.isActive
}
}
}
</script>
使用计算属性过滤列表
通过计算属性对列表数据进行过滤或排序:
<template>
<ul>
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: 'Apple', category: 'fruit' },
{ id: 2, name: 'Carrot', category: 'vegetable' }
],
filterCategory: 'fruit'
}
},
computed: {
filteredItems() {
return this.items.filter(item => item.category === this.filterCategory)
}
}
}
</script>
嵌套列表渲染
对于嵌套数据结构,可以使用多层 v-for:
<template>
<div v-for="group in groups" :key="group.id">
<h3>{{ group.name }}</h3>
<ul>
<li v-for="item in group.items" :key="item.id">
{{ item.name }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
groups: [
{
id: 1,
name: 'Group 1',
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' }
]
}
]
}
}
}
</script>
性能优化注意事项
- 始终为
v-for提供唯一的:key属性,帮助 Vue 高效更新 DOM - 对于大型列表,考虑使用虚拟滚动技术(如
vue-virtual-scroller) - 避免在
v-for中使用复杂计算,优先使用计算属性
这些方法覆盖了 Vue 中实现列表展示的主要场景,可以根据具体需求选择合适的方式。







