vue实现分类的逻辑
Vue 实现分类逻辑的方法
数据准备与分类渲染
在 Vue 中实现分类功能,通常需要准备分类数据和对应的列表数据。分类数据可以是一个数组,每个分类对象包含唯一标识和名称。列表数据需要包含与分类关联的字段。
data() {
return {
categories: [
{ id: 1, name: '电子产品' },
{ id: 2, name: '家居用品' }
],
items: [
{ id: 1, name: '手机', categoryId: 1 },
{ id: 2, name: '电视', categoryId: 1 },
{ id: 3, name: '沙发', categoryId: 2 }
],
activeCategory: null
}
}
分类筛选方法
通过计算属性实现分类筛选,根据当前选中的分类返回对应的列表项。使用 filter 方法对列表进行筛选,只保留与当前分类匹配的项。
computed: {
filteredItems() {
if (!this.activeCategory) return this.items
return this.items.filter(item =>
item.categoryId === this.activeCategory
)
}
}
模板渲染

在模板中使用 v-for 渲染分类选项和筛选后的列表项。为分类选项绑定点击事件,更新当前选中的分类。
<div>
<button
v-for="category in categories"
:key="category.id"
@click="activeCategory = category.id"
>
{{ category.name }}
</button>
</div>
<ul>
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }}
</li>
</ul>
动态分类切换
通过点击分类按钮切换当前分类,Vue 的响应式系统会自动更新计算属性 filteredItems,从而实现动态分类展示。可以添加高亮样式来标识当前选中的分类。

<button
v-for="category in categories"
:key="category.id"
@click="activeCategory = category.id"
:class="{ active: activeCategory === category.id }"
>
{{ category.name }}
</button>
.active {
background-color: #42b983;
color: white;
}
默认分类显示
初始化时可以设置默认选中的分类,或者显示所有分类项。通过判断 activeCategory 是否为 null 来决定是否显示全部项。
created() {
this.activeCategory = this.categories[0]?.id || null
}
嵌套分类结构
对于多级分类,可以使用递归组件实现。分类数据需要包含子分类字段,通过组件递归渲染每一级分类。
data() {
return {
categories: [
{
id: 1,
name: '电子产品',
children: [
{ id: 3, name: '手机' },
{ id: 4, name: '电脑' }
]
}
]
}
}
<category-tree :categories="categories"></category-tree>






