elemnetui table 排序,含處理null undefined值
阿新 • • 發佈:2022-04-11
<el-table
....省略其他配置
@sort-change="onSortChange"
>
</el-table>
方法:
onSortChange(column) {
if (column.order !== null && column.prop) {
let data1 = [];
let data2 = [];
for (let i = 0; i < this.tableData.length; i++) {
let temp = null;
temp = this.tableData[i][column.prop];
if (temp === null || typeof temp == "undefined") {
data2.push(this.tableData[i]);
} else {
data1.push(this.tableData[i]);
}
}
if (column.order === "ascending") {
data1 = data1.sort(this.compare(column.prop, "ascending"));
} else {
data1 = data1.sort(this.compare(column.prop, "descending"));
}
this.$nextTick(() => {
this.tableData = data1.concat(data2);
});
}
if (column.order === null) {
this.tableData = this.dataCopy2; // dataCopy2存放的是tableData 深拷貝副本,建議從網路請求回來後的值直接深拷貝,不排序時恢復到初始狀態
}
},
compare(property, type, prop) {
return function (obj1, obj2) {
if (type === "ascending") {
return obj1[property] - obj2[property];
} else {
return obj2[property] - obj1[property];
}
};
},