温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2021-07-20 09:45:13 来源:亿速云 阅读:375 作者:小新 栏目:web开发

小编给大家分享一下如何解决vue elementUI中table里数字、字母、中文混合排序问题,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

1.使用场景

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

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

2.代码解析

<el-table
   ref="multipleTable"
   border
   tooltip-effect="dark"
   class="xg-table"
   
   max-height="600">
   <el-table-column
    type="selection"
    width="60" />
   <el-table-column
    :default-sort = "{prop: 'DevName'}"
    :sort-method="sortDevName"
    prop="DevName"
    label="名称"
    sortable
    show-overflow-tooltip />
</el-table>

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

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

<script>
  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]
  }
    }
  }
</script>

3.页面效果

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

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

以上是“如何解决vue elementUI中table里数字、字母、中文混合排序问题”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI