vue实现列表分类
Vue 实现列表分类的方法
使用计算属性分类
通过计算属性对原始数组进行分组处理,返回分类后的数据结构。例如按商品类别分类:
computed: {
categorizedList() {
return this.originalList.reduce((acc, item) => {
if (!acc[item.category]) {
acc[item.category] = []
}
acc[item.category].push(item)
return acc
}, {})
}
}
模板中通过嵌套 v-for 渲染:
<div v-for="(items, category) in categorizedList" :key="category">
<h3>{{ category }}</h3>
<div v-for="item in items" :key="item.id">
{{ item.name }}
</div>
</div>
使用过滤器方法
创建分类过滤器方法,在模板中直接调用:
methods: {
filterByCategory(category) {
return this.list.filter(item => item.category === category)
}
}
模板使用:
<div v-for="category in categories" :key="category">
<h3>{{ category }}</h3>
<div v-for="item in filterByCategory(category)" :key="item.id">
{{ item.name }}
</div>
</div>
使用第三方库
借助 lodash 的 groupBy 实现快速分类:
import _ from 'lodash'
computed: {
groupedList() {
return _.groupBy(this.list, 'category')
}
}
动态分类实现
当分类标准需要动态变化时,可以使用响应式变量:
data() {
return {
groupKey: 'category' // 可动态修改为其他字段
}
},
computed: {
dynamicGroup() {
return this.list.reduce((acc, item) => {
const key = item[this.groupKey]
acc[key] = acc[key] || []
acc[key].push(item)
return acc
}, {})
}
}
带排序的分类实现
分类同时保持每组内部排序:
computed: {
sortedGroups() {
const groups = {}
this.list
.sort((a, b) => a.name.localeCompare(b.name))
.forEach(item => {
const group = item.category
groups[group] = groups[group] || []
groups[group].push(item)
})
return groups
}
}
服务器端分类
当数据量较大时,建议在后端完成分类,前端接收已分类的数据结构:

async fetchData() {
const res = await axios.get('/api/items?group=category')
this.groupedData = res.data
}
每种方法适用于不同场景,计算属性方式最常用且性能较好,适合前端数据量适中的情况。大数据量建议采用服务器端分类方案。






