vue elementUI中table里数字、字母、中文混合排序问题 您所在的位置:网站首页 名字首字母排序规律 vue elementUI中table里数字、字母、中文混合排序问题

vue elementUI中table里数字、字母、中文混合排序问题

2024-06-03 00:15| 来源: 网络整理| 查看: 265

1.使用场景

使用elementUI中的table时,给包含数字字母中文的名称等字段排序

例如:数字(0->9)->大写字母(A->Z)->小写字母(a->z)->中文拼音(a->z)

2.代码解析

设置属性sortable,会按照自带的机制排序,不符合我们的预期;

所以增加属性 sort-method,在方法中自定义排序方式

export default { methods: { sortDevName(str1, str2) { let res = 0 for (let i = 0; ;i++) { if (!str1[i] || !str2[i]) { res = str1.length - str2.length break } const char1 = str1[i] const char1Type = this.getChartType(char1) const char2 = str2[i] const char2Type = this.getChartType(char2) // 类型相同的逐个比较字符 if (char1Type[0] === char2Type[0]) { if (char1 === char2) { continue } else { if (char1Type[0] === 'zh') { res = char1.localeCompare(char2) } else if (char1Type[0] === 'en') { res = char1.charCodeAt(0) - char2.charCodeAt(0) } else { res = char1 - char2 } break } } else { // 类型不同的,直接用返回的数字相减 res = char1Type[1] - char2Type[1] break } } return res }, getChartType(char) { // 数字可按照排序的要求进行自定义,我这边产品的要求是 // 数字(0->9)->大写字母(A->Z)->小写字母(a->z)->中文拼音(a->z) if (/^[\u4e00-\u9fa5]$/.test(char)) { return ['zh', 300] } if (/^[a-zA-Z]$/.test(char)) { return ['en', 200] } if (/^[0-9]$/.test(char)) { return ['number', 100] } return ['others', 999] } } } 3.页面效果

                原列表                   ==》》            正序                 ==》》         倒序

 

混合排序一般都是后台直接返回了,如果需要前端排序的时候可以用下,希望对大家有用~

欢迎大家留言讨论



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有