【排序】表格动态排序

在th上手动添加排序图标和提示图标 ,然后按需在数据对象里增添属性sort or tip

<template>
  <table>
    <tr>
      <th v-for="(item, index) of tableHead" :key="item.value">
        {{item.head}}
        <!-- 排序 -->
        <span class="sortHead" v-if="item.sort">
          <i :class="['sortIcon', 'ascending', activeSort===`ascending${index}`?'activeAscend':'']" @click="sortQuery(item, index, 'ascending')"></i>
          <i :class="['sortIcon', 'descending', activeSort===`descending${index}`?'activeDescend':'']" @click="sortQuery(item, index, 'descending')"></i>
        </span>
        <!-- 提示 -->
        <i v-if="item.tip" class="el-icon-warning-outline" style="font-size: 5px" :title="item.tip"></i>
      </th>
    </tr>
    <tbody>
      <tr><td>...</td> </tr>
    </tbody>
  </table>
</template>

<script>
  export default {
    data() {
      return {
        // 哪列需要排序和提示就加上sort和tip属性
        tableHead: [
          {value: 'name', head: '名称', sort: true},
          {value: 'data', head: '数据', tip: 'xxx'},
          {value: 'date', head: '日期'}
        ],
        activeSort: null,
        oldActiveSort: null
      }
    },

    methods: {
      sortQuery(item, index, type) {
        if (`${type}${index}` === this.oldActiveSort) {
          // 相等说明连续点击了两下,复原成原始状态不升序也不降序
          this.activeSort = null
          this.oldActiveSort = null
        } else {
          this.activeSort = `${type}${index}`
          this.oldActiveSort = `${type}${index}`
        }
        let sortObj = {}
        if (type === 'ascending' && this.activeSort !== null) {
          sortObj.ordering = item.name
        } else if (type === 'descending' && this.activeSort !== null) {
          sortObj.ordering = `-${item.name}`
        }
        this.fetchData(sortObj)
      },

      fetchData(query) {
        // ...
      }
    }
  }
</script>
<style>
  .sortHead{
    display: inline-flex;
    flex-direction: column;
    flex: 1;
    align-items: center;
    vertical-align: middle;
    cursor: pointer;
    position: relative;
    box-sizing: border-box;
  }
  .sortIcon {
    width: 0;
    height: 0;
    border: 5px solid transparent;
    position: absolute;
    left: 5px;
  }
  .ascending {
    border-bottom-color: #c0c4cc;
    top: -12px;
  }
  .descending {
    border-top-color: #c0c4cc;
    bottom: -10px;
  }
  .activeAscend {
    border-bottom-color: #0f73ee;
  }
  .activeDescend {
    border-top-color: #0f73ee;
  }
</style>

ui显示如图 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值