vue:实现商城分类
实现商城分类的基本思路
商城分类功能通常涉及前端展示分类列表、分类商品数据获取以及交互逻辑。Vue.js 结合状态管理(如 Vuex 或 Pinia)和路由(Vue Router)可以高效实现这一需求。
数据结构设计
分类数据通常采用树形结构,包含父分类和子分类。例如:
[
{
"id": 1,
"name": "电子产品",
"children": [
{"id": 101, "name": "手机"},
{"id": 102, "name": "电脑"}
]
}
]
后端 API 应提供分类数据接口(如 /api/categories)和分类商品接口(如 /api/category/:id/products)。
分类列表组件实现
创建 CategoryList.vue 组件展示分类树:

<template>
<div class="category-list">
<div
v-for="category in categories"
:key="category.id"
@click="selectCategory(category)"
>
{{ category.name }}
<!-- 递归子分类 -->
<CategoryList
v-if="category.children"
:categories="category.children"
@select="selectCategory"
/>
</div>
</div>
</template>
<script>
export default {
name: 'CategoryList',
props: ['categories'],
methods: {
selectCategory(category) {
this.$emit('select', category);
}
}
}
</script>
商品列表组件实现
创建 ProductList.vue 组件展示当前分类的商品:
<template>
<div class="product-list">
<div v-for="product in products" :key="product.id">
<h3>{{ product.name }}</h3>
<p>价格: {{ product.price }}</p>
</div>
</div>
</template>
<script>
export default {
name: 'ProductList',
props: ['products']
}
</script>
状态管理与数据获取
使用 Pinia 或 Vuex 管理分类和商品数据:
// stores/categoryStore.js (Pinia 示例)
import { defineStore } from 'pinia'
import { ref } from 'vue'
import axios from 'axios'
export const useCategoryStore = defineStore('category', {
state: () => ({
categories: [],
currentCategory: null,
products: []
}),
actions: {
async fetchCategories() {
const res = await axios.get('/api/categories')
this.categories = res.data
},
async fetchProducts(categoryId) {
const res = await axios.get(`/api/category/${categoryId}/products`)
this.products = res.data
}
}
})
页面整合与路由
在页面中组合组件,并通过路由传递分类 ID:

<template>
<div class="shop-page">
<CategoryList
:categories="categories"
@select="handleCategorySelect"
/>
<ProductList :products="products" />
</div>
</template>
<script>
import { useCategoryStore } from '@/stores/categoryStore'
import { mapState, mapActions } from 'pinia'
export default {
computed: {
...mapState(useCategoryStore, ['categories', 'products'])
},
methods: {
...mapActions(useCategoryStore, ['fetchCategories', 'fetchProducts']),
handleCategorySelect(category) {
this.fetchProducts(category.id)
}
},
mounted() {
this.fetchCategories()
}
}
</script>
交互优化
-
高亮当前选中分类
在CategoryList组件中动态添加选中样式:<div :class="{ 'active': isActive(category) }"> -
面包屑导航
添加Breadcrumb组件显示分类路径:<Breadcrumb :items="breadcrumbItems" /> -
加载状态
在数据获取时显示加载动画:<Loader v-if="loading" />
性能优化建议
- 对分类数据使用
keep-alive缓存 - 实现虚拟滚动处理大量分类
- 使用防抖优化分类切换时的商品请求
- 对商品列表进行分页加载
通过以上步骤,可以构建一个完整的商城分类系统,具备良好的用户体验和可维护性。






