比较好用的调节Table表格的表头和内容的宽度的方法

因为大部分的Table组件的表头宽度不太适合我们所使用的,我们可以通过封装函数来适应表头的宽度。

getColumnWidth(label, prop, tableData) {

      //label表头名称

      //prop对应的内容

      //tableData表格数据

      const minWidth = 150; // 最小宽度

      const padding = 20; // 列内边距

      let arr = tableData.map((item) => item[prop]);

      arr.push(label); //拼接内容和表头数据

      const contentWidths = arr.map((item) => {

        const value = item ? String(item) : "";

        const textWidth = this.getTextWidth(value);

        return textWidth + padding;

      });

      const maxWidth = Math.max(...contentWidths);

      return Math.max(minWidth, maxWidth);

    },

getTextWidth(text) {

      const span = document.createElement("span");

      span.style.visibility = "hidden";

      span.style.position = "absolute";

      span.style.top = "-9999px";

      span.style.whiteSpace = "nowrap";

      span.innerText = text;

      document.body.appendChild(span);

      const width = span.offsetWidth + 40;

      document.body.removeChild(span);

      return width;

    },

通过绑定width的方法实现自适应文字宽度 :width="getColumnWidth("表头名称", "表头字段名", "绑定table的数组")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值