主要实现了el-table的多列排序,并在前端对数据进行排序。代码是四处复制的,仅供参考。
HTML:下面这三个是和排序有关的。
@sort-change="sortChange"
:header-cell-class-name="handleHeaderCellClass"
sortable="custom"
<el-table :data="showData"
v-loading="loading"
size="small"
:row-key="tableData.xxx"
border
@sort-change="sortChange"
:header-cell-class-name="handleHeaderCellClass"
@header-dragend="headerDragend"
style="width: 100%"
height="100%">
<el-table-column
v-for="(item, index) in colList"
:fixed="item.fixed"
:key="`col_${index}`"
:prop="item.prop"
:label="item.label"
:width="item.width"
sortable="custom"
>
JS:用到的两个方法
handleHeaderCellClass({row, column, rowIndex, columnIndex}) {
this.orderArray.forEach((element) => {
if (column.property === element.prop) {
column.order = element.order;
}
});
},
sortChange({column, prop, order}) {
//记录排序字段与排序方式,存入数组
if (order) {
//参与排序
let flagIsHave = false;
this.orderArray.forEach((element) => {
if (element.prop === prop) {
element.order = order;
flagIsHave = true;
}
});
if (!flagIsHave) {
this.orderArray.push({
prop: prop,
order: order,
});
}
} else {
//不参与排序
this.orderArray = this.orderArray.filter((element) => {
return element.prop !== prop
});
}
//要通过后端进行排序操作的话, 可以将this.orderArray传到后端
console.log(this.orderArray);
//处理前端要展示的数据,对数据进行排序
this.currentPage = 1//回到第一页
this.tableData.sort((a, b) => {
const sortFun = (index) => {
const currentSort = this.orderArray[index]
// 如果当前相同,则递归向下排序
if (a[currentSort.prop] === b[currentSort.prop]) {
// 如果没有下级了,直接按照当前层级进行排序
if (this.orderArray.length - 1 >= index + 1) {
return sortFun(index + 1)
}
}
// 根据排序规则进行排序
if (currentSort.order === 'ascending') {
if (a[currentSort.prop] > b[currentSort.prop]) {
return 1
} else {
return -1
}
} else {
if (a[currentSort.prop] > b[currentSort.prop]) {
return -1
} else {
return 1
}
}
}
// 排序递归方法
return sortFun(0)
})
//showData为要展示的数据,这里是通过前端分页的
this.showData = this.tableData.slice(0, this.pageSize)
},
最后的效果
都是复制粘贴缝合出来的,有不对的地方多多见谅。
参考: