elementui table 合并相同的部门单元格
时间: 2023-06-21 19:14:06 浏览: 99
在 ElementUI Table 中合并相同部门的单元格可以通过自定义 Table 的 slot-scope 和 template 实现。具体操作如下:
1. 通过设置 `rowspan` 属性来合并单元格。在模板中定义一个变量 `currentDepartment` 来保存当前的部门名称。
```html
<template slot-scope="{ row, $index }">
<td v-if="$index === 0 || row.department !== currentDepartment" :rowspan="getDepartmentRowCount(row)">
{{ row.department }}
</td>
<td>{{ row.name }}</td>
<td>{{ row.age }}</td>
</template>
```
2. 在 methods 中定义一个函数 `getDepartmentRowCount(row)` 来获取当前部门的行数,用于设置 `rowspan` 属性。
```javascript
methods: {
getDepartmentRowCount(row) {
let count = 1;
if (row.department === this.currentDepartment) {
count = 0;
} else {
this.currentDepartment = row.department;
}
for (let i = this.tableData.indexOf(row) + 1; i < this.tableData.length; i++) {
if (this.tableData[i].department === row.department) {
count++;
} else {
break;
}
}
return count;
}
}
```
完整代码示例如下:
```html
<template>
<el-table :data="tableData" style="width: 100%">
<el-table-column label="姓名" prop="name"></el-table-column>
<el-table-column label="年龄" prop="age"></el-table-column>
<el-table-column label="部门">
<template slot-scope="{ row, $index }">
<td v-if="$index === 0 || row.department !== currentDepartment" :rowspan="getDepartmentRowCount(row)">
{{ row.department }}
</td>
<td>{{ row.name }}</td>
<td>{{ row.age }}</td>
</template>
</el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ name: '张三', age: 18, department: '技术部' },
{ name: '李四', age: 20, department: '技术部' },
{ name: '王五', age: 22, department: '市场部' },
{ name: '赵六', age: 24, department: '市场部' }
],
currentDepartment: ''
};
},
methods: {
getDepartmentRowCount(row) {
let count = 1;
if (row.department === this.currentDepartment) {
count = 0;
} else {
this.currentDepartment = row.department;
}
for (let i = this.tableData.indexOf(row) + 1; i < this.tableData.length; i++) {
if (this.tableData[i].department === row.department) {
count++;
} else {
break;
}
}
return count;
}
}
};
</script>
```
阅读全文