vue循环实现分类表格
Vue 循环实现分类表格的方法
使用 v-for 嵌套循环
在 Vue 中可以通过嵌套 v-for 实现分类表格。需要准备分组数据,通常是一个对象或数组,包含分类名称和对应的子项列表。
<template>
<table>
<tr v-for="(group, groupName) in groupedData" :key="groupName">
<td colspan="2">{{ groupName }}</td>
</tr>
<tr v-for="item in group.items" :key="item.id">
<td>{{ item.name }}</td>
<td>{{ item.value }}</td>
</tr>
</table>
</template>
<script>
export default {
data() {
return {
groupedData: {
'Category A': {
items: [
{ id: 1, name: 'Item 1', value: 'Value 1' },
{ id: 2, name: 'Item 2', value: 'Value 2' }
]
},
'Category B': {
items: [
{ id: 3, name: 'Item 3', value: 'Value 3' }
]
}
}
}
}
}
</script>
使用计算属性处理数据
如果原始数据是扁平数组,可以通过计算属性转换为分组格式。

computed: {
groupedData() {
return this.originalData.reduce((acc, item) => {
if (!acc[item.category]) {
acc[item.category] = { items: [] }
}
acc[item.category].items.push(item)
return acc
}, {})
}
}
添加样式区分分类
为分类行添加特殊样式增强可读性。

.group-header {
font-weight: bold;
background-color: #f0f0f0;
}
<tr class="group-header" v-for="(group, groupName) in groupedData" :key="groupName">
<td colspan="2">{{ groupName }}</td>
</tr>
处理空分组情况
添加逻辑处理可能存在的空分组。
computed: {
nonEmptyGroups() {
return Object.entries(this.groupedData)
.filter(([_, group]) => group.items.length > 0)
.reduce((acc, [name, group]) => {
acc[name] = group
return acc
}, {})
}
}
动态列渲染
当列数不确定时,可以动态渲染表头和数据列。
<table>
<thead>
<tr>
<th v-for="col in columns" :key="col.key">{{ col.title }}</th>
</tr>
</thead>
<tbody>
<template v-for="(group, groupName) in groupedData">
<tr class="group-header" :key="groupName">
<td :colspan="columns.length">{{ groupName }}</td>
</tr>
<tr v-for="item in group.items" :key="item.id">
<td v-for="col in columns" :key="col.key">{{ item[col.key] }}</td>
</tr>
</template>
</tbody>
</table>
以上方法提供了在 Vue 中实现分类表格的完整方案,可以根据实际需求选择适合的方式或组合使用。关键点在于合理组织数据结构,并通过 Vue 的响应式特性和模板语法实现动态渲染。






