vue实现列表分类
Vue 实现列表分类的方法
使用计算属性分类
通过计算属性对原始数组进行分类处理,返回分组后的对象或数组。适用于静态数据或需要响应式更新的场景。
computed: {
categorizedItems() {
return this.items.reduce((acc, item) => {
const category = item.category || '未分类'
if (!acc[category]) acc[category] = []
acc[category].push(item)
return acc
}, {})
}
}
模板中使用 v-for 嵌套渲染:
<div v-for="(group, category) in categorizedItems" :key="category">
<h3>{{ category }}</h3>
<ul>
<li v-for="item in group" :key="item.id">{{ item.name }}</li>
</ul>
</div>
使用过滤器方法
定义分类方法在需要时调用,适合需要动态改变分类逻辑的场景。
methods: {
filterByCategory(category) {
return this.items.filter(item => item.category === category)
}
}
使用第三方库
借助 lodash 的 groupBy 实现更简洁的分类:
import { groupBy } from 'lodash'
computed: {
groupedItems() {
return groupBy(this.items, 'category')
}
}
动态分类选择
添加交互控件让用户选择分类方式:
<select v-model="currentCategory">
<option value="all">全部</option>
<option v-for="cat in uniqueCategories" :value="cat">{{ cat }}</option>
</select>
<ul>
<li v-for="item in filteredList" :key="item.id">{{ item.name }}</li>
</ul>
computed: {
uniqueCategories() {
return [...new Set(this.items.map(item => item.category))]
},
filteredList() {
return this.currentCategory === 'all'
? this.items
: this.items.filter(item => item.category === this.currentCategory)
}
}
分类性能优化
对于大型列表,使用虚拟滚动或分页加载:
<RecycleScroller
class="scroller"
:items="groupedItems"
:item-size="50"
key-field="id">
<template v-slot="{ item }">
<div>{{ item.name }}</div>
</template>
</RecycleScroller>
服务端分类
当数据量极大时,建议在服务端完成分类:
async fetchCategorizedData() {
const res = await axios.get('/api/items', {
params: { groupBy: 'category' }
})
this.groupedData = res.data
}






