vue实现分类列表
Vue 实现分类列表的方法
数据结构设计
使用数组存储分类数据,每个分类对象包含 id、name 等属性,子分类通过 children 字段嵌套。例如:
categories: [
{
id: 1,
name: "电子产品",
children: [
{ id: 101, name: "手机" },
{ id: 102, name: "笔记本电脑" }
]
}
]
模板渲染
通过 v-for 递归渲染多级分类,结合 v-if 控制子分类的显示状态:
<ul>
<li v-for="category in categories" :key="category.id">
{{ category.name }}
<ul v-if="category.children">
<li v-for="child in category.children" :key="child.id">
{{ child.name }}
</li>
</ul>
</li>
</ul>
动态交互
添加展开/折叠功能,通过 data 中的 expandedIds 数组记录展开状态:

data() {
return {
expandedIds: []
}
},
methods: {
toggleExpand(id) {
const index = this.expandedIds.indexOf(id);
index === -1
? this.expandedIds.push(id)
: this.expandedIds.splice(index, 1);
}
}
样式优化
使用 CSS 增强视觉效果,如缩进表示层级关系:
ul {
list-style-type: none;
padding-left: 20px;
}
li {
cursor: pointer;
margin: 5px 0;
}
组件化拆分
将分类项拆分为独立组件 CategoryItem,通过 props 接收数据:

// CategoryItem.vue
props: ['category'],
template: `
<li @click.stop="toggleExpand(category.id)">
{{ category.name }}
<ul v-if="isExpanded && category.children">
<category-item
v-for="child in category.children"
:key="child.id"
:category="child"
/>
</ul>
</li>
`
数据加载
通过 API 异步获取分类数据,使用 axios 或 fetch:
async created() {
try {
const res = await axios.get('/api/categories');
this.categories = res.data;
} catch (error) {
console.error("加载分类失败", error);
}
}
状态管理
对于大型应用,建议使用 Vuex 集中管理分类状态:
// store.js
state: {
categories: []
},
mutations: {
SET_CATEGORIES(state, data) {
state.categories = data;
}
}






