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-list">
<div v-for="category in categories" :key="category.id">
<div @click="toggleChildren(category)">
{{ category.name }}
<span v-if="category.children && category.children.length">
{{ category.showChildren ? '▼' : '▶' }}
</span>
</div>
<div v-show="category.showChildren" class="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>
样式优化
添加CSS增强用户体验:

.category-list {
padding-left: 20px;
}
.children {
margin-left: 15px;
}
.category-item {
cursor: pointer;
padding: 5px 0;
}
.category-item:hover {
background-color: #f5f5f5;
}
与商品列表联动
在父组件中实现分类选择与商品展示的联动:
<template>
<div>
<category-list
:categories="categories"
@select="handleCategorySelect"
/>
<product-list :products="filteredProducts" />
</div>
</template>
<script>
export default {
data() {
return {
selectedCategoryId: null,
// ...其他数据
}
},
computed: {
filteredProducts() {
return this.products.filter(p =>
!this.selectedCategoryId ||
p.categoryId === this.selectedCategoryId
)
}
},
methods: {
handleCategorySelect(categoryId) {
this.selectedCategoryId = categoryId
}
}
}
</script>
性能优化建议
对于大型分类数据,考虑使用虚拟滚动技术:

import { VirtualList } from 'vue-virtual-scroll-list'
export default {
components: { VirtualList },
// 实现方式...
}
动态加载分类
实现分类数据的懒加载:
methods: {
async loadChildren(category) {
if (!category.children || category.children.length === 0) {
const res = await api.getSubCategories(category.id)
this.$set(category, 'children', res.data)
}
this.$set(category, 'showChildren', true)
}
}
移动端适配
针对移动设备添加触摸事件支持:
<template>
<div
@click="handleClick"
@touchstart="handleTouchStart"
@touchend="handleTouchEnd"
>
<!-- 内容 -->
</div>
</template>






