vue栏目分类实现
Vue栏目分类实现
数据准备
栏目分类数据通常以树形结构存储,后端返回的数据格式可能如下:
[
{
"id": 1,
"name": "科技",
"children": [
{
"id": 3,
"name": "人工智能"
}
]
},
{
"id": 2,
"name": "财经"
}
]
递归组件实现
创建Category.vue递归组件处理多级分类:
<template>
<ul>
<li v-for="item in categories" :key="item.id">
{{ item.name }}
<category
v-if="item.children && item.children.length"
:categories="item.children"
/>
</li>
</ul>
</template>
<script>
export default {
name: 'Category',
props: {
categories: {
type: Array,
required: true
}
}
}
</script>
状态管理
对于复杂场景可使用Vuex管理分类状态:

// store/modules/categories.js
export default {
state: {
list: []
},
mutations: {
SET_CATEGORIES(state, payload) {
state.list = payload
}
},
actions: {
async fetchCategories({ commit }) {
const res = await api.getCategories()
commit('SET_CATEGORIES', res.data)
}
}
}
动态路由整合
结合vue-router实现分类路由:
const routes = [
{
path: '/category/:id',
component: () => import('@/views/CategoryPage.vue'),
props: true
}
]
性能优化
对于大型分类树可使用虚拟滚动:

<template>
<RecycleScroller
:items="flattenCategories"
:item-size="50"
key-field="id"
>
<template v-slot="{ item }">
<div :style="{ paddingLeft: `${item.level * 20}px` }">
{{ item.name }}
</div>
</template>
</RecycleScroller>
</template>
交互增强
添加折叠功能改进用户体验:
<script>
export default {
data() {
return {
expandedIds: new Set()
}
},
methods: {
toggleExpand(id) {
this.expandedIds.has(id)
? this.expandedIds.delete(id)
: this.expandedIds.add(id)
}
}
}
</script>
样式处理
使用CSS变量实现主题化:
.category-item {
--indent: 20px;
padding-left: calc(var(--level) * var(--indent));
transition: all 0.3s ease;
}
.category-item:hover {
background-color: var(--hover-bg);
}






