vue实现点击分类
Vue 实现点击分类功能
基本思路
通过 Vue 的数据绑定和事件处理机制,可以轻松实现点击分类功能。核心是利用 v-for 渲染分类列表,v-on 或 @click 绑定点击事件,动态更新当前选中分类的状态。
实现步骤
1. 准备分类数据
在 Vue 组件的 data 中定义分类列表和当前选中分类的变量:
data() {
return {
categories: [
{ id: 1, name: '全部' },
{ id: 2, name: '科技' },
{ id: 3, name: '体育' },
{ id: 4, name: '娱乐' }
],
currentCategory: null
}
}
2. 渲染分类列表
使用 v-for 循环渲染分类按钮,并通过 :class 动态绑定选中样式:
<div class="category-list">
<button
v-for="category in categories"
:key="category.id"
@click="selectCategory(category)"
:class="{ 'active': currentCategory === category }"
>
{{ category.name }}
</button>
</div>
3. 处理点击事件
在 methods 中定义分类选择方法:

methods: {
selectCategory(category) {
this.currentCategory = category;
// 这里可以添加加载对应分类数据的逻辑
this.loadItemsByCategory(category.id);
},
loadItemsByCategory(categoryId) {
// 实际项目中这里通常是 API 请求
console.log('加载分类ID:', categoryId);
}
}
4. 样式示例 为选中状态添加视觉反馈:
.category-list button {
padding: 8px 16px;
margin-right: 10px;
background: #f5f5f5;
border: none;
cursor: pointer;
}
.category-list button.active {
background: #42b983;
color: white;
}
高级实现(带默认选中)
1. 设置默认选中
在 created 生命周期钩子中设置默认选中的分类:

created() {
this.currentCategory = this.categories[0];
this.loadItemsByCategory(this.currentCategory.id);
}
2. 使用计算属性过滤数据 如果分类数据已经全部加载,可以使用计算属性实现客户端过滤:
computed: {
filteredItems() {
if (!this.currentCategory) return this.allItems;
return this.allItems.filter(item =>
this.currentCategory.id === 1 || // "全部"分类
item.categoryId === this.currentCategory.id
);
}
}
组件化实现
对于复杂项目,可以将分类选择器抽离为独立组件:
<!-- CategorySelector.vue -->
<template>
<div class="category-selector">
<button
v-for="category in categories"
@click="$emit('select', category)"
:class="{ active: category.id === selectedCategoryId }"
>
{{ category.name }}
</button>
</div>
</template>
<script>
export default {
props: {
categories: Array,
selectedCategoryId: Number
}
}
</script>
在父组件中使用:
<category-selector
:categories="categories"
:selected-category-id="currentCategoryId"
@select="handleCategorySelect"
/>
这种方法实现了关注点分离,使代码更易维护。






