element-plus 官方表格排序问题

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];
  }
};
相关推荐
祈澈菇凉1 小时前
Webpack的基本功能有哪些
前端·javascript·vue.js
小纯洁w2 小时前
Webpack 的 require.context 和 Vite 的 import.meta.glob 的详细介绍和使用
前端·webpack·node.js
想睡好2 小时前
css文本属性
前端·css
qianmoQ2 小时前
第三章:组件开发实战 - 第五节 - Tailwind CSS 响应式导航栏实现
前端·css
记得早睡~2 小时前
leetcode150-逆波兰表达式求值
javascript·算法·leetcode
zhoupenghui1682 小时前
golang时间相关函数总结
服务器·前端·golang·time
White graces3 小时前
正则表达式效验邮箱格式, 手机号格式, 密码长度
前端·spring boot·spring·正则表达式·java-ee·maven·intellij-idea
庸俗今天不摸鱼3 小时前
Canvas进阶-4、边界检测(流光,鼠标拖尾)
开发语言·前端·javascript·计算机外设
bubusa~>_<3 小时前
解决npm install 出现error,比如:ERR_SSL_CIPHER_OPERATION_FAILED
前端·npm·node.js
yanglamei19623 小时前
基于Python+Django+Vue的旅游景区推荐系统系统设计与实现源代码+数据库+使用说明
vue.js·python·django