原文链接

    1. <template>
    2. <div>
    3. <el-table :data="tableData" border style="width: 60%" :span-method="objectSpanMethod">
    4. <el-table-column prop="name" label="姓名" />
    5. <el-table-column prop="amount1" label="数值1" />
    6. <el-table-column prop="amount2" label="数值2" />
    7. </el-table>
    8. </div>
    9. </template>
    10. <script>
    11. export default {
    12. data() {
    13. return {
    14. tableData: [
    15. { name: "Tom", amount1: 10, amount2: 15 },
    16. { name: "Tom", amount1: 11, amount2: 16 },
    17. { name: "Jack", amount1: 12, amount2: 17 },
    18. { name: "Andy", amount1: 13, amount2: 18 },
    19. { name: "Andy", amount1: 14, amount2: 19 },
    20. ],
    21. };
    22. },
    23. mounted() {
    24. console.log("结果:", this.getSpanNumber(this.tableData, "name"));
    25. },
    26. methods: {
    27. //合并方法
    28. objectSpanMethod({ row, column, rowIndex, columnIndex }) {
    29. if (columnIndex == 0) {
    30. //合并相同的名字
    31. let nameSpan = this.getSpanNumber(this.tableData, "name");
    32. return {
    33. rowspan: nameSpan[rowIndex],
    34. colspan: 1,
    35. };
    36. }
    37. },
    38. //获取要合并的行数
    39. getSpanNumber(data, prop) {
    40. //data要处理的数组,prop要合并的属性,比如name
    41. //数组的长度,有时候后台可能返回个null而不是[]
    42. let length = Array.isArray(data) ? data.length : 0;
    43. if (length > 0) {
    44. //用于标识位置
    45. let position = 0;
    46. //用于对比的数据
    47. let temp = data[0][prop];
    48. //要返回的结果
    49. let result = [1];
    50. //假设数据是AABCC,我们的目标就是返回20120
    51. for (let i = 1; i < length; i++) {
    52. if (data[i][prop] == temp) {
    53. //标识位置的数据加一
    54. result[position] += 1;
    55. //当前位置添0
    56. result[i] = 0;
    57. } else {
    58. //不相同时,修改标识位置,该位置设为1,修改对比值
    59. position = i;
    60. result[i] = 1;
    61. temp = data[i][prop];
    62. }
    63. }
    64. //返回结果
    65. return result;
    66. } else {
    67. return [0];
    68. }
    69. },
    70. },
    71. };
    72. </script>

    结果:

    Element-ui单元格合并 - 图1