首先,在<el-table>
标签中添加@header-dragend
事件,用于监听列宽调整的结束事件。multipleTable记得先初始化为''
<el-table
ref="multipleTable"
:data="tableData"
:header-cell-style="{ background: '#F5F7FA' }"
tooltip-effect="dark"
border
@header-dragend="handleHeaderDragend"
>
然后,在methods
中添加handleHeaderDragend
方法,用于保存调整后的列宽。
methods: {
// ...
handleHeaderDragend(newWidth, oldWidth, column, event) {
const columnKey = column.property;
const columnWidths = JSON.parse(localStorage.getItem('columnWidths')) || {};
columnWidths[columnKey] = newWidth;
localStorage.setItem('columnWidths', JSON.stringify(columnWidths));
},
}
接下来,在created
钩子函数中,获取之前保存的列宽,并将其应用到相应的列上。
如果报错就换为mounted,可能在created
钩子函数中,this.$refs.multipleTable
还没有被赋值。
created() {
// ...
const columnWidths = JSON.parse(localStorage.getItem('columnWidths')) || {};
Object.keys(columnWidths).forEach((columnKey) => {
const column = this.$refs.multipleTable.columns.find((col) => col.property === columnKey);
if (column) {
column.width = columnWidths[columnKey];
}
});
}
最后,需要在beforeDestroy
钩子函数中,保存当前的列宽到localStorage
中。
beforeDestroy() {
const columnWidths = {};
this.$refs.multipleTable.columns.forEach((column) => {
if (column.width) {
columnWidths[column.property] = column.width;
}
});
localStorage.setItem('columnWidths', JSON.stringify(columnWidths));
}
如果页面较多,或者需要封装代码可以改为:
JSON.parse(localStorage.getItem('columnWidths')) || {};
有特殊要求可以改为:
JSON.parse(localStorage.getItem(`${this.$route.name}-columnWidths`)) || {};
目前到这里就结束了。但是如果你觉得这样对你来说有点丑,你既要可以拖动的功能,又要下面的表格不要边框。就像:
你可以在css中加入这段代码:
<style lang="scss">
.el-table__body-wrapper .el-table__row .el-table__cell {
border-left-color: transparent !important;
border-right-color:transparent !important ;
}
</style>
他设置边框颜色为透明来达到了不是那么死板的感觉。
如果你还需要选中某行之后某行颜色变为其他的颜色,可以和别的行区分开,那么:
1.你需要在el-table中加入:row-class-name="rowClassName"
<el-table
ref="multipleTable"
:data="tableData"
:header-cell-style="{ background: '#F5F7FA' }"
tooltip-effect="dark"
border
@header-dragend="handleHeaderDragend"
@selection-change="handleSelectionChange"
:row-class-name="rowClassName"
>
2.加入空输入用于装载数据,然后数据对比,对选中行的颜色进行改变:
selectedRows: [] // 添加这一行
// 选中的行
handleSelectionChange(selection) {
this.selectedRows = selection; // 更新被选中的行
// console.log(selection,'selection');
},
// 改变选中行的颜色
rowClassName({ row }) {
if (this.selectedRows.includes(row)) {
return 'row-selected';
}
return '';
},