table.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { type VxeGridInstance, type VxeGridProps } from 'vxe-table'
  2. /**
  3. * 根据表格内容自动调整列宽
  4. * @param tableData 表格整体数据
  5. * @param grid 表格实例
  6. * @returns
  7. */
  8. export const autoWidth = (tableData: VxeGridProps, grid: VxeGridInstance) => {
  9. const columns = tableData.columns
  10. const data = tableData.data
  11. const columnsWidth: { width: number; field: any }[] = []
  12. if (!columns || !data) return
  13. columns.forEach((column: any) => {
  14. if (column?.field) {
  15. let curStr = ''
  16. let width = 0
  17. const field = column.field
  18. // 判断表头的宽度
  19. if (column.title.length < 12) {
  20. width = column.title.length * 11 + 40
  21. } else if (column.title.length < 20) {
  22. width = column.title.length * 8 + 40
  23. } else {
  24. width = column.title.length * 7 + 40
  25. }
  26. const curData = data.length > 1000 ? data.slice(0, 1000) : data
  27. // 判断表格内容的宽度
  28. // 找到最长的字符串
  29. curData.forEach((row: any) => {
  30. curStr.length < row[field]?.toString().length && (curStr = row[field].toString())
  31. })
  32. // column.title.length > curStr.length && (curStr = column.title)
  33. // 表头的宽度如果小于表格内容的宽度
  34. if (width < curStr.length * 11 + 20) {
  35. // width = curStr.length * 10 + 20
  36. if (curStr.length > 20) {
  37. width = curStr.length * 9 + 40
  38. } else {
  39. width = curStr.length * 11 + 20
  40. }
  41. }
  42. // 宽度不能小于100
  43. // width < 100 && (width = 100)
  44. // 最终宽度不能超过400
  45. width > 400 && (width = 400)
  46. columnsWidth.push({
  47. width,
  48. field: field
  49. })
  50. }
  51. })
  52. columnsWidth.forEach((item) => {
  53. const curColumn: any = columns.find((column: any) => column.field === item.field)
  54. curColumn.minWidth = item.width
  55. })
  56. // 表格重新刷新列配置
  57. grid.reloadColumn(columns)
  58. }