有个需求:实现id排序 数字>字母 大写字母>小写字母 但是大写字母对应的小写字母在下一个字母前 如a>B
排序前
升排序后
<template>
<div class="table">
<el-table
:data="tableData"
style="width: 100%"
stripe
@sort-change="onSortChange"
>
<el-table-column
prop="Id"
label="Id"
sortable="custom"
width="180"
:sort-orders="['ascending', 'descending']"
>
</el-table-column>
<el-table-column prop="date" label="日期" sortable width="180">
</el-table-column>
<el-table-column prop="name" label="姓名" width="180"> </el-table-column>
<el-table-column prop="address" label="地址" :formatter="formatter">
</el-table-column>
</el-table>
</div>
</template>
<script>
// 排序 先数字后字母 先大写A后小a
export default {
name: "index",
data() {
return {
tableData: [
{
date: "2016-05-02",
Id: "1",
name: "王小虎",
address: "上海市普陀区金沙江路 1518 弄",
},
{
date: "2016-05-04",
Id: "12",
name: "王小虎",
address: "上海市普陀区金沙江路 1517 弄",
},
{
date: "2016-05-01",
Id: "123123",
name: "王小虎",
address: "上海市普陀区金沙江路 1519 弄",
},
{
date: "2016-05-03",
Id: "A",
name: "王小虎",
address: "上海市普陀区金沙江路 1516 弄",
},
{
date: "2016-05-03",
Id: "B",
name: "王小虎",
address: "上海市普陀区金沙江路 1516 弄",
},
{
date: "2016-05-03",
Id: "T1",
name: "王小虎",
address: "上海市普陀区金沙江路 1516 弄",
},
{
date: "2016-05-03",
Id: "TD",
name: "王小虎",
address: "上海市普陀区金沙江路 1516 弄",
},
{
date: "2016-05-03",
Id: "a",
name: "王小虎",
address: "上海市普陀区金沙江路 1516 弄",
},
{
date: "2016-05-03",
Id: "b",
name: "王小虎",
address: "上海市普陀区金沙江路 1516 弄",
},
{
date: "2016-05-03",
Id: "c",
name: "王小虎",
address: "上海市普陀区金沙江路 1516 弄",
},
],
};
},
methods: {
onSortChange({ prop, order }) {
if (prop === "Id") {
// 对展示的源数据进行重新排序
this.tableData.sort(this.sortFun(prop, order === "ascending"));
}
},
sortFun(prop, order) {
if (order) {
order = 1;
} else {
order = -1;
}
let that = this;
return function (a, b) {
let res = 0;
for (let i = 0; that.tableData; i++) {
if (!a[prop][i] || !b[prop][i]) {
res = a[prop].length - b[prop].length;
break;
}
let char1 = a[prop][i];
let char1Type = that.getChartType(char1);
let char2 = b[prop][i];
let char2Type = that.getChartType(char2);
// 类型相同的逐个比较字符
if (char1Type[0] === char2Type[0]) {
if (char1 === char2) {
res = 0;
continue;
} else {
if (char1Type[0] === "zh") {
res = char1.localeCompare(char2);
} else if (char1Type[0] === "en") {
let code1 = char1;
let code2 = char2;
if (char1.charCodeAt(0) < 97) {
//大写字母
code1 = char1.toLowerCase();
}
if (char2.charCodeAt(0) < 97) {
code2 = char2.toLowerCase();
}
res = code1.charCodeAt(0) - code2.charCodeAt(0);
} else {
res = char1 - char2;
}
break;
}
} else {
// 类型不同的,直接用返回的数字相减
var num1 = char1Type[1];
var num2 = char2Type[1];
res = num1 - num2;
break;
}
}
return res * order;
};
},
getChartType(char) {
// 数字可按照排序的要求进行自定义 ;数字(0->9)->大写字母(A->Z)->小写字母(a->z)->中文拼音(a->z)
if (/^[0-9]$/.test(char)) {
return ["number", 1];
}
if (/^[a-zA-Z]$/.test(char)) {
return ["en", 2];
}
if (/^[u4e00-u9fa5]$/.test(char)) {
return ["zh", 3];
}
return ["others", 4];
},
formatter(row, column) {
return row.address;
},
},
};
</script>
<style scoped></style>