ElementUI中el-table表格操作列实现宽度自适应

1.表格中操作列部分代码: 

                    <el-table-column fixed="right"
                                     label="操作"
                                     :render-header="renderHeader"
                    >
                        <template #default="scope">
                            <div class="undertake-btns">
                                <el-button v-if="true"
                                           type="text"
                                           size="small"
                                           @click="viewClick(scope.row)"
                                >
                                    查看
                                </el-button>
                                ...
                            </div>
                        </template>
                    </el-table-column>

2.js中部分代码: 

  methods: {
    // 表头部重新渲染
    renderHeader(h, { column, $index }) {
      // 获取操作按钮组的元素
      const opts = document.getElementsByClassName('undertake-btns');
      const widthArr = [];

      // 遍历每个按钮容器,计算其实际宽度并动态设置样式
      Array.prototype.forEach.call(opts, function (item, index) {
        if (item.innerText) {
          // 强制重新布局以获取准确的宽度
          item.style.display = 'inline-block';
          item.style.whiteSpace = 'nowrap';
          widthArr.push(item.offsetWidth);

          // 恢复原来的样式
          item.style.display = '';
          item.style.whiteSpace = '';

          // 设置其他样式...
          ...
        }
      });

      // 重新设置列标题及宽度属性
      if (widthArr.length > 0) {
        column.width = Math.max(...widthArr) + 22;
      } else {
        column.width = 100; // 没有按钮时设置固定宽度为 100px
      }

      // 返回列标题内容
      return h('span', column.label);
    },

    // 查看点击
    viewClick(row) {
      ......
    },

}

3.css样式:

/* 设置操作列按钮样式 */
.undertake-btns {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值