| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- import { type VxeGridInstance, type VxeGridProps } from 'vxe-table'
- /**
- * 根据表格内容自动调整列宽
- * @param tableData 表格整体数据
- * @param grid 表格实例
- * @returns
- */
- export const autoWidth = (tableData: VxeGridProps, grid: VxeGridInstance, customizeWidth?: { [key: string]: number }) => {
- const columns = tableData.columns
- const data = tableData.data
- const columnsWidth: { width: number; field: any }[] = []
- if (!columns || !data) return
- columns.forEach((column: any) => {
- if (column?.field) {
- let curStr = ''
- let width = 0
- const field = column.field
- // 判断表头的宽度
- if (column.title.length < 12) {
- width = column.title.length * 11 + 40
- } else if (column.title.length < 20) {
- width = column.title.length * 10 + 30
- } else {
- width = column.title.length * 7 + 40
- }
- const curData = data.length > 1000 ? data.slice(0, 1000) : data
- // 判断表格内容的宽度
- // 找到最长的字符串
- curData.forEach((row: any) => {
- curStr.length < row[field]?.toString().length && (curStr = row[field].toString())
- })
- // column.title.length > curStr.length && (curStr = column.title)
- // 表头的宽度如果小于表格内容的宽度
- if (width < curStr.length * 11) {
- if (curStr.length > 20) {
- width = curStr.length * 9 + 40
- } else {
- width = curStr.length * 11 + 20
- }
- }
- // 宽度不能小于100
- // width < 100 && (width = 100)
- // 最终宽度不能超过400
- width > 400 && (width = 400)
- // 如果字段是Mode,则固定宽度为80
- if (field === 'Mode') {
- width = 80
- }
- // 如果有自定义宽度,则使用自定义宽度
- if (customizeWidth && customizeWidth[field]) {
- width = customizeWidth[field]
- }
- columnsWidth.push({
- width,
- field: field
- })
- }
- })
- columnsWidth.forEach((item) => {
- const curColumn: any = columns.find((column: any) => column.field === item.field)
- curColumn.width = item.width
- })
- // 表格重新刷新列配置
- grid.reloadColumn(columns)
- }
|