vue实现商品分类
Vue实现商品分类的方法
数据结构设计
商品分类通常采用树形结构,包含父子关系。可以使用以下数据结构表示:
categories: [
{
id: 1,
name: '电子产品',
children: [
{ id: 2, name: '手机' },
{ id: 3, name: '电脑' }
]
}
]
组件化实现
创建可复用的分类组件,如Category.vue:
<template>
<div class="category">
<h3>{{ category.name }}</h3>
<div v-if="category.children" class="subcategories">
<Category
v-for="child in category.children"
:key="child.id"
:category="child"
/>
</div>
</div>
</template>
<script>
export default {
name: 'Category',
props: ['category']
}
</script>
状态管理
对于复杂分类系统,建议使用Vuex管理状态:
// store.js
export default new Vuex.Store({
state: {
categories: []
},
mutations: {
SET_CATEGORIES(state, categories) {
state.categories = categories
}
},
actions: {
async fetchCategories({ commit }) {
const res = await axios.get('/api/categories')
commit('SET_CATEGORIES', res.data)
}
}
})
动态加载
实现懒加载子分类,优化性能:
methods: {
loadChildren(category) {
if (!category.children) {
axios.get(`/api/categories/${category.id}/children`)
.then(res => {
this.$set(category, 'children', res.data)
})
}
}
}
样式处理
使用CSS实现分类树样式:
.category {
margin-left: 20px;
padding: 5px;
border-left: 1px solid #eee;
}
.subcategories {
margin-top: 5px;
}
完整示例
主组件调用示例:
<template>
<div>
<Category
v-for="category in categories"
:key="category.id"
:category="category"
/>
</div>
</template>
<script>
import Category from './Category.vue'
export default {
components: { Category },
computed: {
categories() {
return this.$store.state.categories
}
},
created() {
this.$store.dispatch('fetchCategories')
}
}
</script>
这种方法实现了商品分类的组件化、状态管理和动态加载,可以根据实际需求调整数据结构和样式。







