vue实现商城分类
Vue 实现商城分类功能
数据结构设计
商城分类通常采用树形结构,包含父分类和子分类。数据结构示例:
categories: [
{
id: 1,
name: "电子产品",
children: [
{ id: 101, name: "手机" },
{ id: 102, name: "电脑" }
]
},
{
id: 2,
name: "服装",
children: [
{ id: 201, name: "男装" },
{ id: 202, name: "女装" }
]
}
]
分类组件实现
使用递归组件展示多级分类:
<template>
<div class="category">
<ul>
<li v-for="category in categories" :key="category.id">
{{ category.name }}
<category-list v-if="category.children" :categories="category.children"/>
</li>
</ul>
</div>
</template>
<script>
export default {
name: 'CategoryList',
props: ['categories']
}
</script>
分类筛选功能
通过计算属性实现商品筛选:

computed: {
filteredProducts() {
if (!this.selectedCategory) return this.products
return this.products.filter(
product => product.categoryId === this.selectedCategory
)
}
}
路由配置
为每个分类创建独立路由:
{
path: '/category/:id',
name: 'Category',
component: () => import('./views/Category.vue'),
props: true
}
样式优化
添加交互样式提升用户体验:

.category li {
padding: 8px 12px;
cursor: pointer;
transition: background-color 0.3s;
}
.category li:hover {
background-color: #f5f5f5;
}
.active-category {
font-weight: bold;
color: #42b983;
}
移动端适配
实现响应式侧边栏分类:
<template>
<div class="mobile-categories">
<button @click="showCategories = !showCategories">
分类菜单
</button>
<div v-show="showCategories" class="categories-dropdown">
<!-- 分类内容 -->
</div>
</div>
</template>
性能优化
对于大型分类数据,建议:
- 使用虚拟滚动技术
- 实现懒加载子分类
- 添加分类缓存机制
完整示例代码
<template>
<div class="shop-container">
<div class="category-sidebar">
<category-list
:categories="categories"
@select="selectCategory"
/>
</div>
<div class="product-list">
<product-item
v-for="product in filteredProducts"
:key="product.id"
:product="product"
/>
</div>
</div>
</template>
<script>
import CategoryList from './CategoryList.vue'
import ProductItem from './ProductItem.vue'
export default {
components: { CategoryList, ProductItem },
data() {
return {
selectedCategory: null,
categories: [], // 从API获取
products: [] // 从API获取
}
},
methods: {
selectCategory(categoryId) {
this.selectedCategory = categoryId
}
}
}
</script>






