Vue Element UI 表格:合并重复单元格内容 (el-table)
在 Vue 的 Element UI 表格组件 (el-table) 中,如果想要实现单元格的值与上一行的值相同时,合并单元格,可以使用 scoped slot 来自定义单元格的内容,并通过判断当前单元格的值与上一行的值是否相同来决定是否合并单元格。
首先,需要在 el-table-column 中使用 scoped slot 来自定义单元格的内容,例如:
<el-table-column prop='name'>
<template slot-scope='scope'>
<span v-if='scope.row.name !== getPreviousRowValue(scope.$index, 'name')'>{{ scope.row.name }}</span>
<span v-else></span>
</template>
</el-table-column>
在自定义的 slot 中,通过判断当前单元格的值与上一行的值是否相同来决定是否显示单元格的内容。如果当前单元格的值与上一行的值相同,则不显示内容,实现合并单元格的效果。
接下来,需要在 Vue 的 methods 中定义一个方法来获取上一行的值。可以通过传入当前行的索引和列名来获取上一行的值,例如:
methods: {
getPreviousRowValue(rowIndex, columnName) {
if (rowIndex > 0) {
return this.tableData[rowIndex - 1][columnName];
}
return null;
}
}
在该方法中,判断当前行的索引是否大于 0,如果大于 0,则返回上一行对应列的值,否则返回 null。
最后,需要将上述代码应用到实际的 Vue 组件中,例如:
<template>
<div>
<el-table :data='tableData'>
<el-table-column prop='name'>
<template slot-scope='scope'>
<span v-if='scope.row.name !== getPreviousRowValue(scope.$index, 'name')'>{{ scope.row.name }}</span>
<span v-else></span>
</template>
</el-table-column>
<!-- 其他列的定义 -->
</el-table>
</div>
</template>
<script>
export default {
data() {
return {
tableData: [
{ name: 'John', age: 20 },
{ name: 'Peter', age: 25 },
{ name: 'John', age: 30 },
{ name: 'Mary', age: 35 }
]
};
},
methods: {
getPreviousRowValue(rowIndex, columnName) {
if (rowIndex > 0) {
return this.tableData[rowIndex - 1][columnName];
}
return null;
}
}
};
</script>
在上述示例中,根据 'name' 列的值来合并单元格,如果 'name' 列的值与上一行的值相同,则合并单元格,否则显示当前行的值。
原文地址: https://www.cveoy.top/t/topic/Aiv 著作权归作者所有。请勿转载和采集!