vue 实现商城分类
实现商城分类的基本思路
在Vue中实现商城分类功能,通常需要结合组件化开发、数据管理和UI交互设计。商城分类一般包括多级分类展示、分类切换联动、商品列表筛选等功能。
分类数据结构设计
典型的多级分类数据结构如下:
categories: [
{
id: 1,
name: "电子产品",
children: [
{
id: 11,
name: "手机",
children: [
{ id: 111, name: "智能手机" },
{ id: 112, name: "功能手机" }
]
},
{
id: 12,
name: "电脑"
}
]
},
{
id: 2,
name: "服装"
}
]
分类组件实现方案
侧边栏分类导航
使用递归组件实现多级分类展示:
<template>
<div class="category-sidebar">
<category-item
v-for="category in categories"
:key="category.id"
:category="category"
/>
</div>
</template>
<script>
import CategoryItem from './CategoryItem.vue'
export default {
components: { CategoryItem },
props: ['categories']
}
</script>
递归组件CategoryItem:
<template>
<div class="category-item">
<div @click="toggle">{{ category.name }}</div>
<div v-if="isOpen && category.children" class="sub-categories">
<category-item
v-for="child in category.children"
:key="child.id"
:category="child"
/>
</div>
</div>
</template>
<script>
export default {
name: 'CategoryItem',
props: ['category'],
data() {
return {
isOpen: false
}
},
methods: {
toggle() {
this.isOpen = !this.isOpen
}
}
}
</script>
分类内容区域
<template>
<div class="category-content">
<h2>{{ currentCategory.name }}</h2>
<div v-if="currentCategory.children" class="sub-categories">
<button
v-for="sub in currentCategory.children"
:key="sub.id"
@click="selectSubCategory(sub)"
>
{{ sub.name }}
</button>
</div>
<product-list :products="filteredProducts" />
</div>
</template>
分类与商品联动
使用Vuex管理分类状态和商品筛选:
// store/modules/category.js
const state = {
currentCategoryId: null
}
const getters = {
filteredProducts: (state, getters, rootState) => {
if (!state.currentCategoryId) return rootState.products.all
return rootState.products.all.filter(
p => p.categoryId === state.currentCategoryId
)
}
}
响应式布局优化
使用CSS实现分类导航的响应式设计:
.category-container {
display: flex;
}
.category-sidebar {
width: 250px;
}
@media (max-width: 768px) {
.category-sidebar {
width: 100%;
overflow-x: auto;
white-space: nowrap;
}
}
性能优化建议
- 大型分类数据采用虚拟滚动技术
- 分类数据预加载或懒加载
- 使用keep-alive缓存分类组件
- 分类切换时添加过渡动画
完整示例整合
将上述组件整合到主视图:
<template>
<div class="category-view">
<category-sidebar :categories="categories" />
<category-content
:currentCategory="currentCategory"
:products="filteredProducts"
/>
</div>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters(['categories', 'currentCategory', 'filteredProducts'])
}
}
</script>
通过以上方案可以实现完整的商城分类功能,包括多级分类展示、分类切换和商品筛选等核心功能。根据实际项目需求,可以进一步扩展分类筛选、面包屑导航等功能。







