el-table 表头多字段排序

el-table 表头多字段排序
  1. 实现:借助 el-table 的 sort-change 方法和属性 header-cell-class-name
  2. 具体实现:
<!-- template -->
<el-table @sort-change="sortChange" :header-cell-class-name="handleHeaderCellClass"></el-table>

<!-- data -->
orderList: [], // 需要显示排序的字段
currentOrderList: [], // 已保存的排序

<!-- methods -->
/**
  * @description 表头排序
  */
sortChangeLog(row) {
  if (row.order) {
    // 参与排序
    let flag = false
    this.orderList.forEach((element) => {
      if (row.prop === element.prop) {
        element.order = row.order
        flag = true
        }
      })
      if (!flag) {
        this.orderList.push({
          prop: row.prop,
          order: row.order,
        })
      }
      if (row.order === 'ascending') {
        // 顺序
        this.currentOrderList.push(`${row.prop} asc`)
        // 删除相反排序字段
        this.currentOrderList = _.filter(this.currentOrderList, (item) => {
          return item !== `${row.prop} desc`
        })
      } else if (row.order === 'descending') {
        // 逆序
        this.currentOrderList.push(`${row.prop} desc`)
        // 删除相反排序字段
        this.currentOrderList = _.filter(this.currentOrderList, (item) => {
          return item !== `${row.prop} asc`
        })
      }
    }else {
      // 不参与排序
      this.orderList = this.orderList.filter((element) => {
        return element.prop !== row.prop
      })

      // 删除排序字段
      this.currentOrderList = _.filter(this.currentOrderList, (item) => {
        return item !== `${row.prop} asc` && item !== `${row.prop} desc`
      })
    }
  }
},

/**
  * @description 列表多个字段显示排序箭头
  */
handleHeaderCellClass({ column }) {
  this.orderList.forEach((element) => {
    if (column.property === element.prop) {
      column.order = element.order
    }
  })
},
  1. 在 el-table 自身逻辑中, sort-change 触发后会默认触发 header-cell-class-name 对应的方法
  2. 思路: sort-change 触发时,在 orderList 添加或删除排序字段, 之后在触发 header-cell-class-name 对应的方法时就可以去设置对应的列排序(以及是否排序)
注意

当要清空掉排序的前提下,然后重新渲染列表时,这时候有两种情况:

  1. 如果表格表头是动态渲染,清空排序操作:直接将动态表头先置为[]
  2. 如果表格表头是固定的,清空排序操作: 在 el-table 添加 v-if,获取新的数据前先将 v-if 条件置为 false,数据获取成功再置为 true
  3. el-table 提供的方法 clearSort 只能清除一个列的排序
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容