Vue vxe-table adaptive table content width

learn from

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>

Request the backend to obtain tableData data, obtain the longest content of the corresponding field in the corresponding tableData data according to the header field, and set the width of the table header. It is worth noting that the width of
vxe-table can only accept integer values

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;
    },
  },
};

Guess you like

Origin blog.csdn.net/qq_42611074/article/details/131230904