首页 > 解决方案 > Vue用空单元格排序导致不同的结果

问题描述

我创建了一个根据 asc 和 desc 顺序排序的表。当单元格不为空时它工作正常,但是当它为空时,每次在升序和降序之间切换时结果都会改变。

这是我的排序代码:

methods:{
    sort:function(filter) {
      //if filter == current sort, reverse
      if(filter === this.currentSort) {
        this.currentSortDir = this.currentSortDir==='asc'?'desc':'asc';
      }
      this.currentSort = filter;
    },

和计算:

  computed:{
    sortedPeople:function() { //sort by current sorting direction
       return this.people.sort((a,b) => {

        let modifier = 1;
        if(this.currentSortDir === 'desc') modifier = -1;

        if(a[this.currentSort] == null || b[this.currentSort] == null){
            return -1;
        }

        if(a[this.currentSort] <= b[this.currentSort]){ 

            return -1 * modifier;
        }
        if(a[this.currentSort] > b[this.currentSort]) {

            return 1 * modifier; 
        }
        return 0;
      }).filter((row, index) => { //limit view and not repeat due to pagination
        let start = (this.currentPage-1)*this.pageSize;
        let end = this.currentPage*this.pageSize;
        if(index >= start && index < end) return true;
      });
    }
    }

我试图将空单元格排序到最后,但我的方法不能 100% 工作,我真的不明白为什么它们会在开关之间改变。

编辑:我调整了我的代码,现在它们都被排序在一起,但是它们在开头的“a”之前排序,而不是结尾,我不确定如何将它排序到最后。

sortedPeople:function() { //sort by current sorting direction
   return this.people.sort((a,b) => {

    let modifier = 1;
    if(this.currentSortDir === 'desc') modifier = -1;

    if(a[this.currentSort] == null){ //CHANGED CODE 
        a[this.currentSort] = "";
    } else if (b[this.currentSort] == null){
        b[this.currentSort] = "";
    }

    if(a[this.currentSort] < b[this.currentSort]){ 

        return -1 * modifier;
    }

    if(a[this.currentSort] > b[this.currentSort]) {

        return 1 * modifier; 
    }
    return 0;
  }).filter((row, index) => { //limit view and not repeat due to pagination
    let start = (this.currentPage-1)*this.pageSize;
    let end = this.currentPage*this.pageSize;
    if(index >= start && index < end) return true;
  });
}

标签: javascriptvue.jsvue-component

解决方案


您需要在不考虑排序方向的情况下显式检查空(或null)字符串;类似于以下内容

.sort((a,b) => {
    const aValue = a[this.currentSort];
    const bValue = b[this.currentSort];

    if (aValue === bValue) return 0;

    if (!aValue) return 1;
    if (!bValue) return -1;

    let direction = (aValue < bValue) ? -1 : 1;
    if (this.currentSortDir === 'desc') direction *= -1;
    return direction;
})

推荐阅读