el-table文字根据首字母排序

首先我们看tabledata的返回数据,里面仅包含了单独的列名与每行(rows)的数据,此时我们需要对每列数据进行排序,但我们可操作的仅有rows每行数据,这点要搞清,不用去筛选出来列数据,直接对行数据进行操作

需要考虑两种情况,初始tabledata进行排序与tabledata筛选过之后的filterdata再排序
简单来说就是一次筛选与筛选再筛选

  • 正序A-Z
  • 倒序Z-A

this.rows代表需要筛选的行数据(在初始化时可以拿到)
@change="change"用于el-select变化时拿到值
sort方法对于含有标点符号的字段和中英文混杂的字段不生效

  <!-- 排序气泡框 -->
          <el-popover placement="bottom" title="设置排序条件" width="380" trigger="click">
            <el-select v-model="groupList.value1" placeholder="请选择" size="small" @change="change">
              <el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
            <el-button-group style="margin-left: 10px">
              <el-button type="primary" size="small" @click="upOrder">升序</el-button>
              <el-button type="primary" size="small" @click="downOrder">降序</el-button>
            </el-button-group>
            <el-button type="text" icon="el-icon-delete" style="font-size: 16px; margin-left: 10px"
              @click="deleteOption"></el-button>


            <el-button type="text" :underline="false" slot="reference">排序</el-button>
          </el-popover>
         //定义
         name:'',//用于装el-select 选择后的e
         rows: [],//用于装行数据
         filterData:[]//筛选后的数据
          //方法
   change(e) {
    
    
      this.name = e;
    },
    //取消排序恢复原样
    deleteOption() {
    
    
    //把最初的tabledata赋值给originalValue
      this.tableData = this.originalValue
    },
    // 升序
    upOrder() {
    
    
      if (!this.filterData) {
    
    
        this.tableData = [];
        this.rows.sort((a, b) =>
          a.values[this.name] > b.values[this.name] ? 1 : -1
        );
        for (let i = 0; i < this.rows.length; i++) {
    
    
          this.tableData.push({
    
     rowId: this.rows[i].id, ...this.rows[i].values });
        }
      } else {
    
    
        this.filterData.sort((a, b) => a[this.name].localeCompare(b[this.name]));
      }
    },
    // 降序
    downOrder() {
    
    
      if (!this.filterData) {
    
    
        this.tableData = [];
      this.rows.sort((a, b) =>
        a.values[this.name] < b.values[this.name] ? 1 : -1
      );
      for (let i = 0; i < this.rows.length; i++) {
    
    
        this.tableData.push({
    
     rowId: this.rows[i].id, ...this.rows[i].values });
      }
      }else {
    
    
        this.filterData.sort((a, b) => b[this.name].localeCompare(a[this.name]));
      }
    },

猜你喜欢

转载自blog.csdn.net/Ybittersweet/article/details/129851052