table.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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, customizeWidth?: { [key: string]: number }) => {
  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 * 10 + 30
  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) {
  35. if (curStr.length > 20) {
  36. width = curStr.length * 9 + 40
  37. } else {
  38. width = curStr.length * 11 + 20
  39. }
  40. }
  41. // 宽度不能小于100
  42. // width < 100 && (width = 100)
  43. // 最终宽度不能超过400
  44. width > 400 && (width = 400)
  45. // 如果字段是Mode,则固定宽度为80
  46. if (field === 'Mode') {
  47. width = 80
  48. }
  49. // 如果有自定义宽度,则使用自定义宽度
  50. if (customizeWidth && customizeWidth[field]) {
  51. width = customizeWidth[field]
  52. }
  53. columnsWidth.push({
  54. width,
  55. field: field
  56. })
  57. }
  58. })
  59. columnsWidth.forEach((item) => {
  60. const curColumn: any = columns.find((column: any) => column.field === item.field)
  61. curColumn.width = item.width
  62. })
  63. // 表格重新刷新列配置
  64. grid.reloadColumn(columns)
  65. }