spans.vue 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <template>
  2. <el-table-v2 fixed :columns="columns" :data="data" :width="700" :height="400">
  3. <template #row="props">
  4. <Row v-bind="props" />
  5. </template>
  6. </el-table-v2>
  7. </template>
  8. <script lang="tsx" setup>
  9. import { cloneVNode } from 'vue'
  10. const generateColumns = (length = 10, prefix = 'column-', props?: any) =>
  11. Array.from({ length }).map((_, columnIndex) => ({
  12. ...props,
  13. key: `${prefix}${columnIndex}`,
  14. dataKey: `${prefix}${columnIndex}`,
  15. title: `Column ${columnIndex}`,
  16. width: 150,
  17. }))
  18. const generateData = (columns: ReturnType<typeof generateColumns>, length = 200, prefix = 'row-') =>
  19. Array.from({ length }).map((_, rowIndex) => {
  20. return columns.reduce(
  21. (rowData, column, columnIndex) => {
  22. rowData[column.dataKey] = `Row ${rowIndex} - Col ${columnIndex}`
  23. return rowData
  24. },
  25. {
  26. id: `${prefix}${rowIndex}`,
  27. parentId: null,
  28. }
  29. )
  30. })
  31. const columns = generateColumns(10)
  32. const data = generateData(columns, 200)
  33. const colSpanIndex = 1
  34. columns[colSpanIndex].colSpan = ({ rowIndex }) => (rowIndex % 4) + 1
  35. columns[colSpanIndex].align = 'center'
  36. const rowSpanIndex = 0
  37. columns[rowSpanIndex].rowSpan = ({ rowIndex }) => (rowIndex % 2 === 0 && rowIndex <= data.length - 2 ? 2 : 1)
  38. const Row = ({ rowData, rowIndex, cells, columns }) => {
  39. const colSpan = columns[colSpanIndex].colSpan({ rowData, rowIndex })
  40. if (colSpan > 1) {
  41. let width = Number.parseInt(cells[colSpanIndex].props.style.width)
  42. for (let i = 1; i < colSpan; i++) {
  43. width += Number.parseInt(cells[colSpanIndex + i].props.style.width)
  44. cells[colSpanIndex + i] = null
  45. }
  46. const style = {
  47. ...cells[colSpanIndex].props.style,
  48. width: `${width}px`,
  49. backgroundColor: 'var(--el-color-primary-light-3)',
  50. }
  51. cells[colSpanIndex] = cloneVNode(cells[colSpanIndex], { style })
  52. }
  53. const rowSpan = columns[rowSpanIndex].rowSpan({ rowData, rowIndex })
  54. if (rowSpan > 1) {
  55. const cell = cells[rowSpanIndex]
  56. const style = {
  57. ...cell.props.style,
  58. backgroundColor: 'var(--el-color-danger-light-3)',
  59. height: `${rowSpan * 50}px`,
  60. alignSelf: 'flex-start',
  61. zIndex: 1,
  62. }
  63. cells[rowSpanIndex] = cloneVNode(cell, { style })
  64. } else {
  65. const style = cells[rowSpanIndex].props.style
  66. // override the cell here for creating a pure node without pollute the style
  67. cells[rowSpanIndex] = <div style={{ ...style, width: `${style.width}px` }} />
  68. }
  69. return cells
  70. }
  71. </script>