element-plus 官方API 默认表格排序存在问题,一个list 被多组排序
修改后:
javascript
<template>
<el-table
:data="stateTable.table.data"
@sort-change="(data) => handleSort(data, stateTable)"
>
</el-table>
<template>
<script setup>
import { reactive } from "vue";
import { copyTableData, handleSort } from "@/hooks/useSortTable.js";
let stateTable = reactive({
table: {
border: true,
currentPage: 1,
pageSize: 10,
// 接口返回数据
data: [],
// 表头数据
columns: [],
},
});
const getTableData = async (data) => {
copyTableData.value = [...stateTable.table.data]
};
getTableData()
</script>
useSortTable.js
javascript
import { ref } from "vue";
export const copyTableData = ref([]);
export const sortByFieldDesc = (arr, field, order) => {
arr.sort((a, b) => {
const aValue = a?.[field];
const bValue = b?.[field];
let numA =
typeof aValue === "string" && !isNaN(Number(aValue))
? Number(aValue)
: aValue;
let numB =
typeof bValue === "string" && !isNaN(Number(bValue))
? Number(bValue)
: bValue;
if (
typeof numA === "string" &&
typeof numB === "string" &&
!isNaN(Date.parse(numA)) &&
!isNaN(Date.parse(numB))
) {
// 如果是日期类型的字符串,则按照日期排序
const dateA = new Date(numA);
const dateB = new Date(numB);
if (order === "descending") {
return dateB - dateA;
} else {
return dateA - dateB;
}
} else {
// 非日期类型,按照数字或其他类型的逻辑排序
if (order === "descending") {
return numB - numA;
} else {
return numA - numB;
}
}
});
return arr;
};
// 修改handleSort函数,使其接受stateTable作为参数
export const handleSort = (data, stateTable) => {
const { prop, order } = data;
let reserveData = copyTableData.value.filter(
(item) =>
item?.[prop] !== undefined &&
item?.[prop] !== null &&
item?.[prop] !== "-"
);
let filterData = copyTableData.value.filter(
(item) =>
item?.[prop] === undefined ||
item?.[prop] === null ||
item?.[prop] === "-"
);
if (order !== null) {
sortByFieldDesc(reserveData, prop, order);
stateTable.table.data = reserveData.concat(filterData);
} else {
stateTable.table.data = [...copyTableData.value];
}
};