如何在ElementUI中的Table控件中使用拼音进行排序

时间:2023-03-09 22:54:14
如何在ElementUI中的Table控件中使用拼音进行排序

本人使用版本是1.4.7

在这个版本中对应全是String的column进行排序并不是按照拼音的方式排列的。

这里我贴一下源代码就可以看出是为什么了:

export const orderBy = function(array, sortKey, reverse, sortMethod) {
if (typeof reverse === 'string') {
reverse = reverse === 'descending' ? -1 : 1;
}
if (!sortKey && !sortMethod) {
return array;
}
const order = (reverse && reverse < 0) ? -1 : 1; // sort on a copy to avoid mutating original array
return array.slice().sort(sortMethod ? function(a, b) {
return sortMethod(a, b) ? order : -order;
} : function(a, b) {
if (sortKey !== '$key') {
if (isObject(a) && '$value' in a) a = a.$value;
if (isObject(b) && '$value' in b) b = b.$value;
}
a = isObject(a) ? getValueByPath(a, sortKey) : a;
b = isObject(b) ? getValueByPath(b, sortKey) : b;
return a === b ? 0 : a > b ? order : -order;
});
};

关键就在:

return a === b ? 0 : a > b ? order : -order;

return sortMethod(a, b) ? order : -order;

本人之前直接用

a.brandName.localeCompare(b.brandName)

导致排序出问题,因为源代码中只接受true与false,而且localeCompare会返回1、0、-1,-1会被转化为true,从而造成了bug。正确方式:

return a.brandName.localeCompare(b.brandName)>0 ? 1:0;

将-1转化为0,这样就正确了

ps.需要判断a与b是否为空,如果为null就赋值为‘’

2017/12/14升级了2.08发现源代码的判断方式改掉了,所以需要改成:

return a.brandName.localeCompare(b.brandName)>0;