useTableCheck.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import { ref, computed, watch, nextTick, unref } from 'vue'
  2. import { isDefine } from '@/utils/common'
  3. import type { Ref, ShallowRef, UnwrapRef } from 'vue'
  4. import type { InstanceTable } from 'global-type'
  5. import type { MultipleResult } from 'api-type'
  6. type ArrayObjectType = Array<Record<string, any>>
  7. type MultipleResultType<T = Record<string, any>> = MultipleResult<T>
  8. type InputDataType = MultipleResultType | ArrayObjectType
  9. type TableDataType<T> = Ref<T> | ShallowRef<T>
  10. type ArrayData<T extends InputDataType> = T extends MultipleResultType<infer D> ? D : ExtractArrayValue<T>
  11. type RowType<T extends TableDataType<InputDataType>> = ArrayData<UnwrapRef<T>> & {
  12. index: number
  13. }
  14. function isMultipleData(data: any): data is MultipleResultType {
  15. return isDefine(data?.result) && isDefine(data?.totalCount)
  16. }
  17. const useTableCheck = <T extends TableDataType<InputDataType>>(data: T, auto = true) => {
  18. const tableRef = ref<InstanceTable>()
  19. const elTableRef = computed(() => {
  20. return tableRef?.value?.tableRef
  21. })
  22. const tableData = computed(() => {
  23. const d = unref(data)
  24. let result: RowType<T>[] = []
  25. if (d) {
  26. if (isMultipleData(d)) {
  27. result = d?.result?.map((d, index) => ({ ...d, index: d.index ?? index })) as RowType<T>[]
  28. } else {
  29. result = d?.map((d, index) => ({ ...d, index: d.index ?? index })) as RowType<T>[]
  30. }
  31. }
  32. return result
  33. })
  34. const current = ref<RowType<T>>()
  35. const currentView = ref<RowType<T>>()
  36. const visibleHistory = ref<boolean>(false)
  37. watch(
  38. tableData,
  39. () => {
  40. current.value = void 0
  41. currentView.value = void 0
  42. if (tableData?.value?.length && auto) {
  43. nextTick(() => {
  44. elTableRef?.value?.setCurrentRow(tableData.value[0])
  45. })
  46. }
  47. },
  48. { immediate: true }
  49. )
  50. /** 表格选中 */
  51. const onCurrentChange = (row: RowType<T>) => {
  52. current.value = row
  53. }
  54. /** 表格行双击 */
  55. const onDbClick = (row: RowType<T>) => {
  56. currentView.value = row
  57. visibleHistory.value = true
  58. }
  59. /** 下一份 */
  60. const next = () => {
  61. elTableRef?.value?.setCurrentRow(tableData.value[((current.value?.index || 0) + 1) % tableData.value.length])
  62. }
  63. return {
  64. tableRef,
  65. elTableRef,
  66. tableData,
  67. current,
  68. currentView,
  69. visibleHistory,
  70. onCurrentChange,
  71. onDbClick,
  72. next,
  73. }
  74. }
  75. export default useTableCheck