效果
1、table
(1)排序前
(2)排序后(以年龄排序为示例)
2、descriptions
(1)排序前
(2)排序后
一、运用场景
1、table:根据汉字或者日期排序 - ocaleCompare,new Date / Date.parse
2、descriptions:根据英文首字母排序 - sort
二、完整示例
1、table(localeCompare,new Date / Date.parse)
<template>
<a-table :columns="columns" :data-source="data" />
</template>
<script lang="ts" setup>
import type { TableColumnType, TableProps } from 'ant-design-vue';
type TableDataType = {
key: string;
name: string;
age: number;
birth: string,
regist: string,
address: string;
};
const columns: TableColumnType<TableDataType>[] = [
{
title: '姓名',
dataIndex: 'name',
},
{
title: '年龄',
dataIndex: 'age',
sorter: (a: TableDataType, b: TableDataType) => a.age - b.age,
sortDirections: ['ascend', 'descend'],
},
{
title: '出生日期',
dataIndex: 'birth',
sorter: (a: TableDataType, b: TableDataType) => {
let aBirth = new Date(a.birth).getTime()
let bBirth = new Date(b.birth).getTime()
return aBirth - bBirth
},
sortDirections: ['ascend', 'descend'],
},
{
title: '注册日期',
dataIndex: 'regist',
sorter: (a: TableDataType, b: TableDataType) => {
let aRegist = Date.parse(a.birth)
let bRegist = Date.parse(b.birth)
return aRegist - bRegist
},
sortDirections: ['ascend', 'descend'],
},
{
title: '城市',
dataIndex: 'address',
sorter: (a: TableDataType, b: TableDataType) => {
let prev = a.address ? a.address : '';
let next = b.address ? b.address : '';
return prev.localeCompare(next, 'zh-Hans-CN', { sensitivity: 'accent' });
},
sortDirections: ['ascend', 'descend'],
},
];
const data: TableDataType[] = [
{
key: '1',
name: '张三',
age: 18,
birth: '2005-06-13',
regist: '2005-06-14',
address: '北京市',
},
{
key: '2',
name: '李四',
age: 25,
birth: '2000-04-25',
regist: '2000-04-26',
address: '北京市',
},
{
key: '3',
name: '王五',
age: 28,
birth: '1995-11-08',
regist: '1995-11-09',
address: '上海市',
},
{
key: '4',
name: '赵六',
age: 18,
birth: '2005-02-26',
regist: '2005-02-27',
address: '广州市',
},
];
</script>
2、descriptions
<template>
<a-descriptions title="个人信息" bordered>
<a-descriptions-item v-for="item in data" :label="item.text" :key="item.id">{{ item.value }}</a-descriptions-item>
</a-descriptions>
</template>
<script lang="ts" setup>
let data = [
{
id: "1",
field: "road",
text: "公路",
value: 2
},
{
id: "2",
field: "tree",
text: "树木",
value: 567
},
{
id: "3",
field: "streetamp",
text: "路灯",
value: 160
},
{
id: "3",
field: "shrub",
text: "灌木",
value: 325
},
]
function sortArray(a, b){
return a.field.localeCompare(b.field)
}
function handleSort() {
data = data.sort(sortArray)
}
handleSort();
</script>