vue怎么实现分类
Vue 实现分类的方法
使用计算属性过滤数据
通过计算属性对数据进行分类筛选,适用于静态或动态数据。定义一个计算属性,根据分类条件返回过滤后的数组。
computed: {
filteredItems() {
return this.items.filter(item => item.category === this.selectedCategory);
}
}
使用 v-for 和 v-if 结合
在模板中直接结合 v-for 和 v-if 实现分类渲染,注意 v-if 应放在外层元素或使用 <template> 标签。
<template v-for="item in items">
<div v-if="item.category === 'food'" :key="item.id">
{{ item.name }}
</div>
</template>
动态组件切换
通过动态组件按分类加载不同子组件,适合分类结构差异较大的场景。
<component :is="currentCategoryComponent" />
data() {
return {
currentCategory: 'books',
componentsMap: {
books: 'BooksComponent',
food: 'FoodComponent'
}
};
},
computed: {
currentCategoryComponent() {
return this.componentsMap[this.currentCategory];
}
}
使用路由参数分类
通过 Vue Router 的路径参数实现分类,适合需要 URL 共享的分类状态。
const routes = [
{ path: '/category/:type', component: CategoryPage }
]
第三方库辅助
使用 lodash 的 groupBy 等工具函数快速实现数据分类。

import _ from 'lodash';
computed: {
groupedItems() {
return _.groupBy(this.items, 'category');
}
}
实现要点
- 分类数据建议使用唯一标识符作为
key - 大量数据分类时考虑性能优化,如虚拟滚动
- 动态分类可结合事件总线或 Vuex 管理状态






