index.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { ref, shallowRef } from 'vue'
  2. import type { TableColumnCtx } from 'element-plus/es/components/table/src/table-column/defaults'
  3. import { getTableColumns } from '@/business/table'
  4. import { ComposeTableOptions } from './interface'
  5. /**
  6. * 组合表格函数
  7. * @param rowKey 表格主键key
  8. */
  9. export function useComposeTable<T>({ rowKey, columnKey }: ComposeTableOptions<T>) {
  10. // 表格选中的行数据
  11. const selectedRow = ref<T>()
  12. // 获取表格列数据
  13. const tableColumns = shallowRef(getTableColumns(columnKey))
  14. // 表格展开行,对应 row-key 中的值
  15. const expandKeys = shallowRef<T[keyof T][]>([])
  16. // 右键菜单
  17. const contextmenu = ref({
  18. show: false,
  19. clientX: 0,
  20. clientY: 0,
  21. })
  22. // 表格行点击事件
  23. const rowClick = (row: T) => {
  24. const keyValue = row[rowKey]
  25. if (expandKeys.value.includes(keyValue)) {
  26. expandKeys.value = []
  27. } else {
  28. expandKeys.value = [keyValue]
  29. }
  30. selectedRow.value = row
  31. }
  32. // 表格右键事件
  33. const rowContextmenu = (row: T, column: TableColumnCtx<T>, event: MouseEvent) => {
  34. // 阻止浏览器右键
  35. event.preventDefault()
  36. // 表格选中的行数据
  37. selectedRow.value = row
  38. // 显示表格右键菜单
  39. contextmenu.value = {
  40. show: true,
  41. clientX: event.clientX,
  42. clientY: event.clientY,
  43. }
  44. }
  45. return {
  46. rowKey,
  47. tableColumns,
  48. expandKeys,
  49. selectedRow,
  50. contextmenu,
  51. rowClick,
  52. rowContextmenu,
  53. }
  54. }