dynamic-height.vue 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <template>
  2. <el-table-v2
  3. :columns="columns"
  4. :data="data"
  5. :sort-by="sort"
  6. :estimated-row-height="40"
  7. :width="700"
  8. :height="400"
  9. fixed
  10. @column-sort="onColumnSort"
  11. />
  12. </template>
  13. <script lang="tsx" setup>
  14. import { ref } from 'vue'
  15. import {
  16. ElButton,
  17. ElTag,
  18. TableV2FixedDir,
  19. TableV2SortOrder,
  20. } from 'element-plus'
  21. import type { Column, SortBy } from '@element-plus/components/table-v2'
  22. const longText =
  23. 'Quaerat ipsam necessitatibus eum quibusdam est id voluptatem cumque mollitia.'
  24. const midText = 'Corrupti doloremque a quos vero delectus consequatur.'
  25. const shortText = 'Eius optio fugiat.'
  26. const textList = [shortText, midText, longText]
  27. // generate random number in range 0 to 2
  28. let id = 0
  29. const dataGenerator = () => ({
  30. id: `random:${++id}`,
  31. name: 'Tom',
  32. date: '2016-05-03',
  33. description: textList[Math.floor(Math.random() * 3)],
  34. })
  35. const columns: Column<any>[] = [
  36. {
  37. key: 'id',
  38. title: 'Id',
  39. dataKey: 'id',
  40. width: 150,
  41. sortable: true,
  42. fixed: TableV2FixedDir.LEFT,
  43. },
  44. {
  45. key: 'name',
  46. title: 'Name',
  47. dataKey: 'name',
  48. width: 150,
  49. align: 'center',
  50. cellRenderer: ({ cellData: name }) => <ElTag>{name}</ElTag>,
  51. },
  52. {
  53. key: 'description',
  54. title: 'Description',
  55. dataKey: 'description',
  56. width: 150,
  57. cellRenderer: ({ cellData: description }) => (
  58. <div style="padding: 10px 0;">{description}</div>
  59. ),
  60. },
  61. {
  62. key: 'operations',
  63. title: 'Operations',
  64. cellRenderer: () => (
  65. <>
  66. <ElButton size="small">Edit</ElButton>
  67. <ElButton size="small" type="danger">
  68. Delete
  69. </ElButton>
  70. </>
  71. ),
  72. width: 150,
  73. align: 'center',
  74. },
  75. ]
  76. const data = ref(
  77. Array.from({ length: 200 })
  78. .map(dataGenerator)
  79. .sort((a, b) => (a.name > b.name ? 1 : -1))
  80. )
  81. const sort = ref<SortBy>({ key: 'name', order: TableV2SortOrder.ASC })
  82. const onColumnSort = (sortBy: SortBy) => {
  83. const order = sortBy.order === 'asc' ? 1 : -1
  84. const dataClone = [...data.value]
  85. dataClone.sort((a, b) => (a[sortBy.key] > b[sortBy.key] ? order : -order))
  86. sort.value = sortBy
  87. data.value = dataClone
  88. }
  89. </script>