controlled-sort.vue 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <template>
  2. <el-table-v2
  3. v-model:sort-state="sortState"
  4. :columns="columns"
  5. :data="data"
  6. :width="700"
  7. :height="400"
  8. fixed
  9. @column-sort="onSort"
  10. />
  11. </template>
  12. <script lang="ts" setup>
  13. import { ref } from 'vue'
  14. import { TableV2SortOrder } from 'element-plus'
  15. import type { SortBy, SortState } from 'element-plus'
  16. const generateColumns = (length = 10, prefix = 'column-', props?: any) =>
  17. Array.from({ length }).map((_, columnIndex) => ({
  18. ...props,
  19. key: `${prefix}${columnIndex}`,
  20. dataKey: `${prefix}${columnIndex}`,
  21. title: `Column ${columnIndex}`,
  22. width: 150,
  23. }))
  24. const generateData = (
  25. columns: ReturnType<typeof generateColumns>,
  26. length = 200,
  27. prefix = 'row-'
  28. ) =>
  29. Array.from({ length }).map((_, rowIndex) => {
  30. return columns.reduce(
  31. (rowData, column, columnIndex) => {
  32. rowData[column.dataKey] = `Row ${rowIndex} - Col ${columnIndex}`
  33. return rowData
  34. },
  35. {
  36. id: `${prefix}${rowIndex}`,
  37. parentId: null,
  38. }
  39. )
  40. })
  41. const columns = generateColumns(10)
  42. const data = ref(generateData(columns, 200))
  43. columns[0].sortable = true
  44. columns[1].sortable = true
  45. const sortState = ref<SortState>({
  46. 'column-0': TableV2SortOrder.DESC,
  47. 'column-1': TableV2SortOrder.ASC,
  48. })
  49. const onSort = ({ key, order }: SortBy) => {
  50. sortState.value[key] = order
  51. data.value = data.value.reverse()
  52. }
  53. </script>