Element UI 表格【列宽自适应】

Element UI 表格【列宽自适应】_第1张图片

<template>
  <div class="page">
    <el-table border style="width: 100%" :data="tableData">
      <el-table-column
        v-for="(item, index) in tableTitleList"
        :key="index"
        :label="item.label"
        :type="item.type"
        :prop="item.prop"
        :align="item.align || 'center'"
        :width="flexColumnWidth(item.label, item.prop)"
      />
    el-table>
  div>
template>

<script>
export default {
  data() {
    return {
      tableTitleList: [
        {
          label: "序号",
          type: "index",
        },
        {
          label: "姓名",
          prop: "name",
        },
        {
          label: "座右铭",
          prop: "motto",
        },
      ],
      tableData: [
        {
          name: "李四",
          motto: "人生没有白走的路,每一步都算数",
        },
        {
          name: "王小二",
          motto: "少壮不努力,老大徒伤悲",
        },
        {
          name: "诸葛孔明",
          motto:
            "大事起于难,小事起于易,故欲思其利必虑其害,欲思其成必虑其败。",
        },
      ],
    };
  },
  methods: {
    getMaxLength(arr) {
      return arr.reduce((acc, item) => {
        if (item) {
          const calcLen = this.getTextWidth(item);
          if (acc < calcLen) {
            acc = calcLen;
          }
        }
        return acc;
      }, 0);
    },

    getTextWidth(str) {
      let width = 0;
      const html = document.createElement("span");
      html.innerText = str;
      html.className = "getTextWidth";
      document.querySelector("body").appendChild(html);
      width = document.querySelector(".getTextWidth").offsetWidth;
      document.querySelector(".getTextWidth").remove();
      return width;
    },

    flexColumnWidth(label, prop) {
      // 1.获取该列的所有数据
      const arr = this.tableData.map((x) => x[prop]);
      arr.push(label); // 把每列的表头也加进去算
      // 2.计算每列内容最大的宽度 + 表格的内间距(依据实际情况而定)
      let maxLength = this.getMaxLength(arr);
      return maxLength + 25 + "px";
    },
  },
};
script>

<style scoped>
.page {
  padding: 30px;
}
/* 表头字体加粗 */
::v-deep .el-table thead {
  font-weight: 1000 !important;
}
style> 

你可能感兴趣的:(#,Element,UI,#,已归档链接,vue.js,表格,列宽)