1、源代码

  1. let rowspanArray
  2. function spanRow({ row, column, rowIndex, columnIndex }, data, option) {
  3. if (rowIndex === 0 && columnIndex === 0) {
  4. computeSpanRow(data, option)
  5. }
  6. if (is(option, columnIndex)) {
  7. const rowspan = rowspanArray[columnIndex][rowIndex]
  8. const colspan = rowspan > 0 ? 1 : 0
  9. return {
  10. rowspan: rowspan,
  11. colspan: colspan
  12. }
  13. }
  14. return {
  15. rowspan: 1,
  16. colspan: 1
  17. }
  18. }
  19. function computeSpanRow(data, option) {
  20. rowspanArray = []
  21. let tempRow= []
  22. for (let i = 0; i < data.length; i++) {
  23. for (let j = 0; j < option.length; j++) {
  24. let index = option[j].index;
  25. let field = option[j].field;
  26. if (i === 0) {
  27. tempRow[index] = 0
  28. rowspanArray[index] = []
  29. rowspanArray[index].push(1)
  30. } else {
  31. if (data[i][field] === data[i - 1][field]) {
  32. rowspanArray[index][tempRow[index]] += 1
  33. rowspanArray[index].push(0)
  34. } else {
  35. rowspanArray[index].push(1)
  36. tempRow[index] = i
  37. }
  38. }
  39. }
  40. }
  41. }
  42. function is(option, index) {
  43. for (let i = 0; i < option.length; i++) {
  44. if (option[i].index === index) {
  45. return true
  46. }
  47. }
  48. return false
  49. }
  50. export { spanRow }

2、示例

  1. <template>
  2. <el-table :data="data" :span-method="onSpanMethod">
  3. <el-table-column prop="field1" label="field1"> </el-table-column>
  4. <el-table-column prop="field2" label="field2"> </el-table-column>
  5. <el-table-column prop="field3" label="field3"> </el-table-column>
  6. </el-table>
  7. </template>
  8. <script>
  9. import { spanRow } from "element-ui-table-span-method";
  10. export default {
  11. data() {
  12. return {
  13. data: [
  14. { field1: "A", field2: "a", field3: "1" },
  15. { field1: "A", field2: "a", field3: "2" },
  16. { field1: "A", field2: "b", field3: "3" }
  17. ],
  18. option: [
  19. { index: 0, field: "field1" },
  20. { index: 1, field: "field2" }
  21. ]
  22. };
  23. },
  24. methods: {
  25. onSpanMethod({ row, column, rowIndex, columnIndex }) {
  26. return spanRow(
  27. { row, column, rowIndex, columnIndex },
  28. this.data,
  29. this.option
  30. );
  31. }
  32. }
  33. };
  34. </script>

参见:https://github.com/h69/element-ui-table-span-method