根据表格的Table-column 属性, 我们可以在操作栏中添加 :render-header="renderHeader"
然后通过js获取当前操作栏存在多少个按钮,去动态计算需要设置列宽为多少;
<el-table-column fixed="right" :label="t('table.operation')" :render-header="renderHeader" >
<template #default="scope">
<div class="optionDiv" style="white-space: nowrap; display: inline-block">
<el-button type="success" size="small" :loading="scope.row.loading"
@click="prmContractC.onDetails(scope.row, false)">
详情
</el-button>
<el-button type="primary" size="small" :loading="scope.row.loading" @click="submitBtn(scope.row.id)"
v-if="(scope.row.workflowState == '0' || scope.row.workflowState == '6' || scope.row.workflowState == '11') && userId == scope.row.createBy">
提交审批
</el-button>
<el-button type="primary" size="small" :loading="scope.row.loading" @click="removeBtn(scope.row.id)"
v-if="scope.row.work && scope.row.work.data && scope.row.work.data.length > 0 && scope.row.work.data[0].canCancel">
撤回
</el-button>
<el-button type="primary" size="small" :loading="scope.row.loading"
v-if="scope.row.work && scope.row.work.data && scope.row.work.data.length > 0 && scope.row.work.data[0].canSubmit"
@click="prmContractC.onDetails(scope.row, true)">
审核
</el-button>
</div>
</template>
</el-table-column>
import {h} from "vue";//引入h
export const renderHeader = ({column}: any) => {
const divElement = document.querySelectorAll('.optionDiv');
// 初始化最大按钮数量
let maxButtons = -1;
// 初始化包含最多按钮的元素
let divWithMostButtons;
divElement.forEach((item, index) => {
// 获取当前 元素中的所有 button 元素
const buttons = item.querySelectorAll('button');
// 如果当前中的 button 数量大于已记录的最大数量
if (buttons.length > maxButtons) {
// 更新最大数量
maxButtons = buttons.length;
// 记录包含最多按钮的
divWithMostButtons = item;
}
});
if(divWithMostButtons){
let widthArr = [];
const buttons = divWithMostButtons.querySelectorAll('button');
buttons.forEach(function (item) {
if (item.innerText) {
widthArr.push(item.offsetWidth);
}
});
// 重新设置列标题及宽度属性
if (widthArr.length == 1) {
column.width = widthArr.reduce((accumulator, currentValue) => accumulator + currentValue, 0)+20;
return h('span', column.label);
}else if (widthArr.length > 1) {
column.width = widthArr.reduce((accumulator, currentValue) => accumulator + currentValue, 0) + 30;
return h('span', column.label);
} else {
column.width = 0;
return h('span', column.label);
}
}
};