antd-vue - - - - - a-table排序

antd-vue - - - - - a-table排序

1. 重点代码:

sorter: {
     compare: (a, b) => a.columnsKeys - b.columnsKeys,
     multiple: 1,
},

解析:
compare: 自定义排序函数,用于比较两个对象。
multiple: 排序优先级权重(数字越大优先级越高)。

2. 代码示例:

<template>
  <a-table :columns="columns" :data-source="data" @change="onChange" />
</template>
<script setup>
const columns = [
  {
    title: 'Name',
    dataIndex: 'name',
  },
  {
    title: 'Chinese Score',
    dataIndex: 'chinese',
    sorter: {
      compare: (a, b) => a.chinese - b.chinese,
      multiple: 3,
    },
  },
  {
    title: 'Math Score',
    dataIndex: 'math',
    sorter: {
      compare: (a, b) => a.math - b.math,
      multiple: 2,
    },
  },
  {
    title: 'English Score',
    dataIndex: 'english',
    sorter: {
      compare: (a, b) => a.english - b.english,
      multiple: 1,
    },
  },
];
const data = [
  {
    key: '1',
    name: 'John Brown',
    chinese: 98,
    math: 60,
    english: 70,
    type1: 1,
    type2: 'star',
    type3: '张三',
  },
  {
    key: '2',
    name: 'Jim Green',
    chinese: 98,
    math: 66,
    english: 89,
    type1: 2,
    type2: 'moon',
    type3: '李四',
  },
  {
    key: '3',
    name: 'Joe Black',
    chinese: 98,
    math: 90,
    english: 70,
    type1: 3,
    type2: 'sun',
    type3: '王五',
  },
];
function onChange(pagination, filters, sorter, extra) {
   // 监听表格变化事件,比如分页、排序、过滤等(回调函数)
  console.log('params', pagination, filters, sorter, extra);
}
</script>

上述代码,分别对chinese、math、english三列设置了排序。

  • multiple的值设置的不一样,数值越大,优先级越高。
  • 比如同时对三列都进行排序,先满足chinese的筛选条件,再满足math的筛选条件,再满足english的筛选条件

3. 进阶版写法

当排序的列类型不仅仅为数字类型时,排序就会出现混乱。解决办法就是针对不同类型,设置不同的compare。

columns.map(col => {
  if (['type1'].includes(col.dataIndex)) {
      // 数值型字段排序
      return {
          ...col,
          sorter: {
			compare:(a, b) => Number(a[col.dataIndex]) - Number(b[col.dataIndex]),
			multiple: 1
          }
      };
  } else if (['type2'].includes(col.dataIndex)) {
      // 字符串字段排序
      return {
          ...col,
          sorter: (a, b) => a[col.dataIndex].localeCompare(b[col.dataIndex]),
      };
  } else {
      // 默认处理:假设其他列都可以按照字符串比较来排序
      return {
          ...col,
          sorter: (a, b) => ('' + a[col.dataIndex]).localeCompare('' + b[col.dataIndex]),
      };
  }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值