0%

饿了么element-ui中el-table组件列宽自适应

饿了么element-ui中el-table组件根据列内容实现列宽自适应,本项目将以 ruoyi-ui 修改为例。

单页示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
<el-table
v-loading="loading"
:data="deptList"
row-key="deptId"
resizable
:border="true"
:fit="false"
ref="elTable"
@header-dragend="handleTableHeaderDragend"
>
<el-table-column prop="deptName" label="全称" />
<el-table-column prop="phone" label="手机号" class-name="auto-width" />
</el-table>

<script>
export default {
name: "Dept",
data() {
return {
// 遮罩层
loading: true,
// 表格树数据
deptList: [],
}
},
created() {
this.getSchoolList();
},
methods: {
adjustColumnWidth(table, padding, dragClsName, increaseWidth) {
var padding = padding || 32;
const colgroup = table.querySelector("colgroup");
const colDefs = [...colgroup.querySelectorAll("col")];
const tableScrollWidth = table.scrollWidth;
var totalWidth = 0; // 累计剩余列宽度和
var autoWith = 0; // 自动列宽度
var autoWithClsName = null; // 自动列class-name
colDefs.forEach((col) => {
const clsName = col.getAttribute("name");
const cells = [
...table.querySelectorAll(`td.${clsName}`),
...table.querySelectorAll(`th.${clsName}`),
];
if (cells[0]?.classList?.contains?.("leave-alone")) {
return;
}
const widthList = cells.map((el) => {
return el.querySelector(".cell")?.scrollWidth || 0;
});
const max = Math.max(...widthList);
var elWidth = max + padding;
if (!dragClsName && cells[0]?.classList?.contains?.("auto-width")) {
autoWithClsName = clsName;
autoWith = elWidth;
return;
}
table.querySelectorAll(`col[name=${clsName}]`).forEach((el) => {
const oElWidth = parseInt(el.getAttribute("_width"));
if (oElWidth) {
if (dragClsName === clsName) {
if (oElWidth + increaseWidth >= elWidth) {
elWidth = oElWidth + increaseWidth;
}
} else {
if (dragClsName) {
elWidth = oElWidth;
}
}
}
el.setAttribute("width", elWidth);
el.setAttribute("_width", elWidth);
});
totalWidth += elWidth;
});
if (autoWithClsName && !dragClsName) {
if (tableScrollWidth > totalWidth) {
var willSettingAutoWith = tableScrollWidth - totalWidth + padding;
if (willSettingAutoWith > autoWith) {
autoWith = willSettingAutoWith;
}
}
table.querySelectorAll(`col[name=${autoWithClsName}]`).forEach((el) => {
el.setAttribute("width", autoWith);
el.setAttribute("_width", autoWith);
});
}
},
handleTableHeaderDragend(newWidth, oldWidth, column, event) {
// this.$nextTick((e) => {
setTimeout(() => {
this.adjustColumnWidth(this.$refs.elTable.$el, 6, column.id, newWidth - oldWidth);
}, 100);
// })
},
getSchoolList() {
this.loading = true;
listDeptType(this.queryParams).then(response => {
this.deptList = this.handleTree(response.rows, "deptId");
this.total = response.total;
this.loading = false;
this.$nextTick((e) => {
this.adjustColumnWidth(this.$refs.elTable.$el, 6);
})
})
}
}
}
</script>
<style scoped>
/deep/.el-table .cell {
display: inline-block !important;
white-space: nowrap !important;
width: auto !important;
overflow: auto !important;
}

/deep/.el-table .el-table__body-wrapper {
overflow-x: auto;
}
</style>

挂载全局样式及全局方法

  • src/assets/styles/index.scss

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    .adjust-cw-el-table .cell {
    display: inline-block !important;
    white-space: nowrap !important;
    width: auto !important;
    overflow: auto !important;
    // white-space: pre-wrap !important;
    }

    .adjust-cw-el-table .el-table__body-wrapper {
    overflow-x: auto;
    }
  • src/utils/ruoyi.js

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    // el-table 自适应列宽
    export function adjustColumnWidth(table, padding, dragClsName, increaseWidth) {
    var padding = padding || 32;
    const colgroup = table.querySelector("colgroup");
    const colDefs = [...colgroup.querySelectorAll("col")];
    const tableScrollWidth = table.scrollWidth;
    var totalWidth = 0;
    var autoWith = 0;
    var autoWithClsName = null;
    colDefs.forEach((col) => {
    const clsName = col.getAttribute("name");
    const cells = [
    ...table.querySelectorAll(`td.${clsName}`),
    ...table.querySelectorAll(`th.${clsName}`),
    ];
    if (cells[0]?.classList?.contains?.("leave-alone")) {
    return;
    }
    const widthList = cells.map((el) => {
    return el.querySelector(".cell")?.scrollWidth || 0;
    });
    const max = Math.max(...widthList);
    var elWidth = max + padding;
    if (!dragClsName && cells[0]?.classList?.contains?.("auto-width")) {
    autoWithClsName = clsName;
    autoWith = elWidth;
    return;
    }
    table.querySelectorAll(`col[name=${clsName}]`).forEach((el) => {
    const oElWidth = parseInt(el.getAttribute("_width"));
    if (oElWidth) {
    if (dragClsName === clsName) {
    if (oElWidth + increaseWidth >= elWidth) {
    elWidth = oElWidth + increaseWidth;
    }
    } else {
    if (dragClsName) {
    elWidth = oElWidth;
    }
    }
    }
    el.setAttribute("width", elWidth);
    el.setAttribute("_width", elWidth);
    });
    totalWidth += elWidth;
    });
    if (autoWithClsName && !dragClsName) {
    if (tableScrollWidth > totalWidth) {
    var willSettingAutoWith = tableScrollWidth - totalWidth + padding;
    if (willSettingAutoWith > autoWith) {
    autoWith = willSettingAutoWith;
    }
    }
    table.querySelectorAll(`col[name=${autoWithClsName}]`).forEach((el) => {
    el.setAttribute("width", autoWith);
    el.setAttribute("_width", autoWith);
    });
    }
    }
  • 添加全局方法:src/main.js

    1
    2
    3
    4
    import Vue from 'vue'
    import { parseTime, resetForm, addDateRange, selectDictLabel, selectDictLabels, handleTree, adjustColumnWidth } from "@/utils/ruoyi";

    Vue.prototype.adjustColumnWidth = adjustColumnWidth
  • 示例

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    <template>        
    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange"
    resizable
    :border="true"
    :fit="false"
    ref="elTable"
    @header-dragend="handleTableHeaderDragend"
    class="adjust-cw-el-table"
    >
    <el-table-column type="selection" align="center" />
    <el-table-column label="用户编号" align="center" key="userId" prop="userId" v-if="columns[0].visible" />
    <el-table-column label="账户名" align="center" key="userName" prop="userName" v-if="columns[1].visible" :show-overflow-tooltip="true"></el-table-column>
    <el-table-column align="center" key="nickName" prop="nickName" v-if="columns[2].visible" :show-overflow-tooltip="true">
    <template slot="header">
    <div>姓名</div>
    <div>手机号</div>
    </template>
    <template slot-scope="scope">
    {{ scope.row.nickName }}<br/>{{ scope.row.phonenumber }}
    </template>
    </el-table-column>
    <el-table-column
    label="操作"
    align="center"
    class-name="small-padding auto-width"
    >
    <template slot-scope="scope" v-if="scope.row.userId !== 1">
    <el-button
    size="mini"
    type="text"
    icon="el-icon-edit"
    @click="handleUpdate(scope.row)"
    v-hasPermi="['system:user:edit']"
    >修改</el-button>
    <el-button
    size="mini"
    type="text"
    icon="el-icon-delete"
    @click="handleDelete(scope.row)"
    v-hasPermi="['system:user:remove']"
    >删除</el-button>
    </template>
    </el-table-column>
    </el-table>
    </template>
    <script>
    export default {
    methods: {
    handleTableHeaderDragend(newWidth, oldWidth, column, event) {
    setTimeout(() => {
    this.adjustColumnWidth(this.$refs.elTable.$el, 6, column.id, newWidth - oldWidth);
    }, 100);
    },
    getList() {
    this.loading = true;
    listUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
    this.userList = response.rows;
    this.$nextTick((e) => {
    this.adjustColumnWidth(this.$refs.elTable.$el, 6);
    })
    this.total = response.total;
    this.loading = false;
    }
    );
    },
    }
    }
    </script>

参考