当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 解决vue elementUI中table里数字、字母、中文混合排序问题

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

2020年03月09日  | 移动技术网IT编程  | 我要评论

1.使用场景

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

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

2.代码解析

<el-table
   ref="multipletable"
   border
   tooltip-effect="dark"
   class="xg-table"
   style="width: 100%"
   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里数字、字母、中文混合排序问题,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网