用Vue实现商品分类
使用 Vue 实现商品分类
数据结构设计
商品分类通常采用树形结构,每个分类节点包含 id、name、children 等字段。例如:
const categories = [
{
id: 1,
name: "电子产品",
children: [
{
id: 101,
name: "手机",
children: [
{ id: 1011, name: "智能手机" },
{ id: 1012, name: "功能手机" }
]
}
]
}
]
组件化实现
创建一个递归组件 CategoryTree.vue 来渲染分类树:
<template>
<ul>
<li v-for="category in categories" :key="category.id">
{{ category.name }}
<CategoryTree
v-if="category.children && category.children.length"
:categories="category.children"
/>
</li>
</ul>
</template>
<script>
export default {
name: 'CategoryTree',
props: {
categories: {
type: Array,
required: true
}
}
}
</script>
状态管理
对于大型应用,建议使用 Vuex 管理分类数据:
// store/modules/categories.js
export default {
state: {
categories: []
},
mutations: {
SET_CATEGORIES(state, categories) {
state.categories = categories
}
},
actions: {
async fetchCategories({ commit }) {
const res = await api.getCategories()
commit('SET_CATEGORIES', res.data)
}
}
}
交互功能实现
添加展开/折叠功能:
<template>
<ul>
<li v-for="category in categories" :key="category.id">
<span @click="toggleExpand(category)">
{{ category.name }}
</span>
<CategoryTree
v-if="category.children && category.children.length && category.expanded"
:categories="category.children"
/>
</li>
</ul>
</template>
<script>
export default {
methods: {
toggleExpand(category) {
this.$set(category, 'expanded', !category.expanded)
}
}
}
</script>
API 集成
创建 API 服务层:
// api/categories.js
import axios from 'axios'
export default {
getCategories() {
return axios.get('/api/categories')
},
addCategory(parentId, name) {
return axios.post('/api/categories', { parentId, name })
}
}
样式优化
使用 CSS 增强视觉效果:
ul {
list-style: none;
padding-left: 20px;
}
li {
cursor: pointer;
padding: 5px 0;
}
li > span:hover {
color: #42b983;
font-weight: bold;
}
完整示例
主组件调用示例:
<template>
<div>
<CategoryTree :categories="categories" />
<button @click="refresh">刷新分类</button>
</div>
</template>
<script>
import CategoryTree from './CategoryTree.vue'
import api from '../api/categories'
export default {
components: { CategoryTree },
data() {
return {
categories: []
}
},
created() {
this.refresh()
},
methods: {
async refresh() {
const res = await api.getCategories()
this.categories = res.data
}
}
}
</script>
该实现包含了商品分类的核心功能,可根据实际需求扩展编辑、删除等操作。对于性能优化,可考虑虚拟滚动技术处理大型分类树。







