element plus table 表格操作列根据按钮数量自适应宽度 - 指南

直接上代码
在utils直接封装autoWidthHeaderRender.js文件

/**
* 表格操作列自适应宽度计算函数
* @param {string} className - 操作栏容器类名
* @param {number} padding - 额外padding宽度
* @param {number} minWidth - 最小宽度
* @returns {number} 计算后的宽度
*/
export const calculateOperationWidth = (className = 'operation-cell', padding = 30, minWidth = 120) => {
try {
const cells = document.getElementsByClassName(className)
let maxWidth = minWidth
Array.from(cells).forEach(cell => {
if (cell.offsetParent !== null) { // 只计算可见元素
const buttons = cell.querySelectorAll('.el-button')
let totalWidth = 0
buttons.forEach(button => {
// 计算每个按钮的宽度(包括margin)
const style = window.getComputedStyle(button)
const margin = parseFloat(style.marginLeft) + parseFloat(style.marginRight)
totalWidth += button.offsetWidth + margin
})
maxWidth = Math.max(maxWidth, totalWidth + padding)
}
})
return maxWidth
} catch (error) {
console.error('操作栏宽度计算错误:', error)
return minWidth
}
}

页面里使用 增加class style

去验证
import { calculateOperationWidth } from '@/utils/autoWidthHeaderRender'
const operationWidth = ref(120)
// 计算并更新操作列宽度
const updateOperationWidth = async () => {
await nextTick() // 确保DOM已更新
operationWidth.value = calculateOperationWidth('operation-cell', 30, 120)
}
// 监听数据变化
watch(() => customerList.value, updateOperationWidth, {
deep: true,
immediate: true,
})

这样就可以自适应宽度了,大体思路是这样

posted @ 2025-08-09 20:28  yfceshi  阅读(63)  评论(0)    收藏  举报