Eelement Table 多列组合排序

2,332 阅读1分钟

element-ui table 配合后端实现多列组合排序。

思路:

  1. 监听 sort-change 事件,在该事件中缓存和修正当前的排序规则。并根据保存的排序规则调接口刷新表格数据;
  2. 监听 header-cell-class-name 事件,在该事件中修正表头排序图标的样式。保证图标的样式逻辑和缓存的排序规则一致。

image.png

image.png

<el-table
  :data="pagination.data"
  ref="multipleTable"
  class="orioc-table center-table"
  row-key="id"
  v-loading="listLoading"
  @sort-change='handleSortChange'
  :header-cell-class-name="handleHeadAddClass"
  stripe border>
    <el-table-column
      prop="organizationName"
      label="单位名称"
      min-width="130" sortable
    ></el-table-column>
    
    <el-table-column
      prop="elevatorCount"
      label="台量"
      width="100"
      align="center" sortable
    ></el-table-column>
</el-table>
<script>
  export default {
    data() {
      return {
        sortField: {},
        orderBys: []
      };
    },
    
    methods: {
      handleSortChange({ order, prop }) {
        // 触发的排序和缓存的排序相同时,取消该字段的排序
        if (!order || this.sortField[prop] === order) {
          this.sortField[prop] = null
        } else {
          this.sortField[prop] = order
        }
        // console.log(this.sortField)
        this.orderBys = []
        let direction = ''
        for (const i in this.sortField) {
          if (this.sortField[i] == 'ascending') {
            direction = 'ASC'
          } else if (this.sortField[i] == 'descending') {
            direction = 'DESC'
          }
        this.orderBys.push({
            "column": i,
            "direction": direction
          })
        }
        // console.log(' this.orderBys', this.orderBys)
        this.onSearch() //调用后端查询接口
      },
      
      handleHeadAddClass({ column }) {
        if (this.sortField[column.property]) {
          column.order = this.sortField[column.property]
        }
      },
    }
  };
</script>