vue列表实现
Vue 列表实现方法
在 Vue 中实现列表渲染通常使用 v-for 指令,结合数组或对象生成动态内容。
基础列表渲染
通过 v-for 遍历数组,生成列表项:
<template>
<ul>
<li v-for="item in items" :key="item.id">
{{ item.text }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' },
{ id: 3, text: 'Item 3' }
]
}
}
}
</script>
索引值获取
需要当前项的索引时,可以添加第二个参数:

<li v-for="(item, index) in items" :key="item.id">
{{ index }} - {{ item.text }}
</li>
对象遍历
v-for 也可以遍历对象的属性:
<li v-for="(value, key) in object" :key="key">
{{ key }}: {{ value }}
</li>
性能优化
为每个列表项添加唯一的 key 属性,帮助 Vue 高效更新 DOM:

<li v-for="item in items" :key="item.id">
{{ item.text }}
</li>
列表更新检测
Vue 对数组的变异方法(如 push, pop, shift, unshift, splice, sort, reverse)进行了封装,能触发视图更新:
methods: {
addItem() {
this.items.push({ id: 4, text: 'New Item' })
}
}
显示过滤/排序结果
不改变原始数据的情况下,显示处理后的列表:
<li v-for="n in evenNumbers">{{ n }}</li>
<script>
computed: {
evenNumbers() {
return this.numbers.filter(number => number % 2 === 0)
}
}
</script>
范围 v-for
v-for 也可以接受整数,重复模板多次:
<span v-for="n in 10">{{ n }} </span>






