vue 实现商城分类
Vue 实现商城分类功能
数据结构设计
商城分类通常采用树形结构,需设计包含 id、name、children 等字段的嵌套数据。例如:
[
{
"id": 1,
"name": "电子产品",
"children": [
{
"id": 101,
"name": "手机",
"children": []
}
]
}
]
组件拆分
- 分类侧边栏组件:用于展示一级分类,通过点击切换当前分类。
- 子分类展示组件:根据当前选中的一级分类动态渲染二级或三级分类。
- 商品列表组件:展示当前分类下的商品数据。
动态渲染分类
使用 v-for 递归渲染嵌套分类结构:
<template>
<div v-for="category in categories" :key="category.id">
<div @click="selectCategory(category)">{{ category.name }}</div>
<div v-if="category.children.length > 0" class="sub-categories">
<CategoryList :categories="category.children" />
</div>
</div>
</template>
状态管理
通过 Vuex 或 Pinia 管理当前选中的分类 ID,实现跨组件状态共享:
// Pinia 示例
export const useCategoryStore = defineStore('category', {
state: () => ({
currentCategoryId: null
}),
actions: {
setCurrentCategory(id) {
this.currentCategoryId = id
}
}
})
路由参数绑定
将分类 ID 与路由参数绑定,支持直接访问特定分类页:
const routes = [
{
path: '/category/:id',
component: CategoryPage,
props: true
}
]
数据请求优化
使用 computed 缓存分类数据,避免重复请求:

const categories = computed(() => store.getters.getCategories)
交互增强
- 添加分类展开/折叠动画
- 使用
active类标记当前选中分类 - 实现面包屑导航显示分类路径
移动端适配
- 侧边栏改为滑动抽屉式布局
- 通过手势事件支持左右滑动切换分类
- 使用
vw/vh单位确保布局响应式
完整实现需结合具体业务需求调整数据结构和交互细节。






