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]),
};
}