vue vxe-table自适应表格内容宽度

学习自

https://www.cnblogs.com/huangxiaoxue/p/12034326.html

 <vxe-table
        border
        resizable
        round
        height="100%"
        highlight-hover-row
        align="center"
        :data="tableData"
      >
        <vxe-table-column type="checkbox" width="60"></vxe-table-column>
        <vxe-table-column type="seq" title="序号" width="60"></vxe-table-column>
        <vxe-table-column
          v-for="(item, index) in dealtableColumn"
          :key="item.id"
          :field="item.field"
          :title="item.title"
          :width="item.width"
        ></vxe-table-column>
      </vxe-table>

请求后端获取tableData数据,根据表头字段获取对应tableData数据中相应字段的最长内容,设置表头宽度
值得注意的坑是:vxe-table的宽度只能接受整数值

export default {
    
    
  data() {
    
    
    return {
    
    
      tableData:[],
      dealtableColumn: [],
      tableColumn: [
        {
    
    
          title: "户号",
          field: "consNo",
        },
        {
    
    
          title: "户名",
          field: "consName",
        },
        {
    
    
          title: "地市",
          field: "ds",
        }
      ],
    };
  },
  watch: {
    
    
    tableData(valArr) {
    
    
      this.dealtableColumn = this.tableColumn.map((item) => {
    
    
        const arr = valArr.map((val) => val[item.field]); // 获取每一列的所有数据
        arr.push(item.title); // 把每列的表头也加进去算
        item.width = Math.round(this.getMaxLength(arr) + 40) + "px"; // 每列内容最大的宽度 + 表格的内间距(依据实际情况而定)
        return item;
      });
    },
  },
  methods: {
    
    
    // 遍历列的所有内容,获取最宽一列的宽度
    getMaxLength(arr) {
    
    
      return arr.reduce((acc, item) => {
    
    
        if (item) {
    
    
          let calcLen = this.getTextWidth(item);
          if (acc < calcLen) {
    
    
            acc = calcLen;
          }
        }
        return acc;
      }, 0);
    },
    // 获取文本宽度
    getTextWidth(str) {
    
    
      let width = 0;
      let span = document.createElement("span");
      span.innerText = str;
      document.querySelector("body").appendChild(span);
      width = span.getBoundingClientRect().width;
      span.remove();
      return width;
    },
  },
};

猜你喜欢

转载自blog.csdn.net/qq_42611074/article/details/131230904