vue实现商品分类
Vue 实现商品分类的方法
数据准备
商品分类数据通常以树形结构组织,包含父分类和子分类。数据格式可以设计为:
categories: [
{
id: 1,
name: "电子产品",
children: [
{ id: 11, name: "手机" },
{ id: 12, name: "电脑" }
]
},
{
id: 2,
name: "服装",
children: [
{ id: 21, name: "男装" },
{ id: 22, name: "女装" }
]
}
]
组件结构
创建分类展示组件,使用递归组件处理多级分类:
<template>
<div class="category-list">
<div v-for="category in categories" :key="category.id">
<div @click="toggleChildren(category)">
{{ category.name }}
<span v-if="category.children">+</span>
</div>
<div v-if="category.showChildren && category.children">
<category-list :categories="category.children" />
</div>
</div>
</div>
</template>
<script>
export default {
name: 'CategoryList',
props: ['categories'],
methods: {
toggleChildren(category) {
this.$set(category, 'showChildren', !category.showChildren)
}
}
}
</script>
状态管理
对于大型应用,建议使用Vuex管理分类状态:
// store/modules/categories.js
export default {
state: {
categories: []
},
mutations: {
SET_CATEGORIES(state, categories) {
state.categories = categories
}
},
actions: {
async fetchCategories({ commit }) {
const res = await api.getCategories()
commit('SET_CATEGORIES', res.data)
}
}
}
分类筛选
实现商品按分类筛选功能:
computed: {
filteredProducts() {
if (!this.selectedCategory) return this.products
return this.products.filter(
product => product.categoryId === this.selectedCategory
)
}
}
样式优化
添加CSS样式增强用户体验:
.category-list {
padding-left: 20px;
}
.category-item {
cursor: pointer;
padding: 5px;
}
.category-item:hover {
background-color: #f5f5f5;
}
交互增强
添加动画效果提升用户体验:
<transition name="fade">
<div v-if="category.showChildren && category.children">
<category-list :categories="category.children" />
</div>
</transition>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity .3s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
API集成
从后端API获取分类数据:
methods: {
async loadCategories() {
try {
const response = await axios.get('/api/categories')
this.categories = response.data
} catch (error) {
console.error('加载分类失败:', error)
}
}
},
created() {
this.loadCategories()
}
以上方法提供了完整的商品分类实现方案,可根据实际需求进行调整和扩展。







