vue 实现列表
Vue 实现列表的方法
在 Vue 中实现列表通常使用 v-for 指令,结合数组或对象进行渲染。以下是几种常见的实现方式:
基础列表渲染
通过 v-for 指令遍历数组,动态生成列表项。
<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, index) in object" :key="key">
{{ index }}. {{ key }}: {{ value }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
object: {
name: 'Vue',
version: '3.x',
type: 'Framework'
}
}
}
}
</script>
动态绑定样式或类
可以为列表项动态绑定样式或类,实现条件渲染。

<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 },
{ id: 3, name: 'Item 3', 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' },
{ id: 3, name: 'Banana', category: 'fruit' }
],
selectedCategory: 'fruit'
}
},
computed: {
filteredItems() {
return this.items.filter(item => item.category === this.selectedCategory)
}
}
}
</script>
列表过渡动画
使用 Vue 的 <transition-group> 组件为列表添加过渡效果。
<template>
<button @click="addItem">Add Item</button>
<transition-group name="list" tag="ul">
<li v-for="item in items" :key="item.id" class="list-item">
{{ item.name }}
</li>
</transition-group>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' }
]
}
},
methods: {
addItem() {
this.items.push({ id: this.items.length + 1, name: `Item ${this.items.length + 1}` })
}
}
}
</script>
<style>
.list-item {
transition: all 0.5s;
}
.list-enter-active, .list-leave-active {
transition: all 0.5s;
}
.list-enter, .list-leave-to {
opacity: 0;
transform: translateY(30px);
}
</style>
以上方法涵盖了 Vue 中实现列表的常见需求,包括基础渲染、动态绑定、过滤排序和动画效果。






