vue如何实现列表
实现列表的基本方法
在Vue中实现列表通常使用v-for指令。v-for可以基于数组或对象渲染一个列表。基本语法如下:
<ul>
<li v-for="item in items" :key="item.id">
{{ item.text }}
</li>
</ul>
使用数组渲染列表
最常见的场景是基于数组数据渲染列表。数组中的每个元素可以是简单类型或对象。
<template>
<div>
<ul>
<li v-for="(fruit, index) in fruits" :key="index">
{{ index }}: {{ fruit }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
fruits: ['Apple', 'Banana', 'Orange']
}
}
}
</script>
使用对象渲染列表
v-for也可以遍历对象的属性,提供属性值、属性名和索引。

<template>
<div>
<ul>
<li v-for="(value, name, index) in user" :key="index">
{{ index }}. {{ name }}: {{ value }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
user: {
name: 'John',
age: 30,
gender: 'male'
}
}
}
}
</script>
维护列表状态
为每个列表项添加唯一的key属性很重要,这能帮助Vue高效地更新DOM。通常使用数据中的唯一标识符作为key。
<template>
<div>
<ul>
<li v-for="task in tasks" :key="task.id">
{{ task.name }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
tasks: [
{ id: 1, name: 'Task 1' },
{ id: 2, name: 'Task 2' },
{ id: 3, name: 'Task 3' }
]
}
}
}
</script>
列表过滤与排序
可以使用计算属性对列表数据进行过滤或排序,而不改变原始数据。

<template>
<div>
<input v-model="search" placeholder="Search...">
<ul>
<li v-for="fruit in filteredFruits" :key="fruit">
{{ fruit }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
search: '',
fruits: ['Apple', 'Banana', 'Orange', 'Mango']
}
},
computed: {
filteredFruits() {
return this.fruits.filter(fruit =>
fruit.toLowerCase().includes(this.search.toLowerCase())
)
}
}
}
</script>
动态操作列表
可以通过方法动态添加、删除或更新列表项。
<template>
<div>
<input v-model="newItem" @keyup.enter="addItem">
<button @click="addItem">Add</button>
<ul>
<li v-for="(item, index) in items" :key="index">
{{ item }}
<button @click="removeItem(index)">×</button>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
newItem: '',
items: ['Item 1', 'Item 2', 'Item 3']
}
},
methods: {
addItem() {
if (this.newItem.trim()) {
this.items.push(this.newItem)
this.newItem = ''
}
},
removeItem(index) {
this.items.splice(index, 1)
}
}
}
</script>
使用组件渲染列表
对于复杂列表项,可以创建单独组件来封装列表项的显示逻辑。
<!-- TodoItem.vue -->
<template>
<li>
{{ todo.text }}
<button @click="$emit('remove', todo.id)">×</button>
</li>
</template>
<script>
export default {
props: ['todo']
}
</script>
<!-- TodoList.vue -->
<template>
<div>
<ul>
<todo-item
v-for="todo in todos"
:key="todo.id"
:todo="todo"
@remove="removeTodo"
/>
</ul>
</div>
</template>
<script>
import TodoItem from './TodoItem.vue'
export default {
components: {
TodoItem
},
data() {
return {
todos: [
{ id: 1, text: 'Learn Vue' },
{ id: 2, text: 'Build something' },
{ id: 3, text: 'Profit' }
]
}
},
methods: {
removeTodo(id) {
this.todos = this.todos.filter(todo => todo.id !== id)
}
}
}
</script>






