elementui自定义排序

205 阅读1分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第18天,点击查看活动详情

在写后台管理项目的时候,产品设计的原型上有两列有排序字段,去看elementui的例子之后发现有sortable字段但是是前端的排序,不符合我们需求,因为数据分页了。前端排序只能排序第一页。就想着自己定义一个自定义表头来实现排序功能...

html代码

<el-table-column prop="mileage" label="累计里程" align="center" width="110" show-overflow-tooltip>
    <template slot="header">
        <div class="d-fx-s">
            累计里程
            <div class="sort">
                <div :class="['el-icon-caret-top',sort === 2 ? 'active':'']" @click="onSort(2, 1)"></div>
                <div :class="['el-icon-caret-bottom',sort === 1 ? 'active':'']" @click="onSort(1, 1)"></div>
            </div>
        </div>
    </template>
    <template slot-scope="scope">{{scope.row.mileage | getMileage}}</template>
</el-table-column>
<el-table-column prop="totalTime" label="总时长" align="center" width="100" show-overflow-tooltip >
    <template slot="header">
        <div class="d-fx-s">
            总时长
            <div class="sort">
                <div class="el-icon-caret-top" @click="onSort(4, 2)"></div>
                <div class="el-icon-caret-bottom" @click="onSort(3, 2)"></div>
            </div>
        </div>
    </template>
    <template slot-scope="scope">{{scope.row.totalTime | getTimes}}</template>
</el-table-column>

实现的效果如下: image.png

看着还挺满意的,赶紧试了试,效果可以,可是...

点击排序图标之后,数据正确了,但是图标的颜色并没有变

原来是因为,点击排序图标之后,列表掉接口,重新渲染表格了,这可咋整,这也看不出当前是根据什么排序的呀。

无奈又去看文档,居然发现了elementui自带的sort属性。

image.png 列表有sort-change方法。 image.png 赶紧去试了下

html代码

<el-table
        ref="multipleTable"
        :data="tableData"
        :height="height"
        border
        resizable
        @sort-change="sortChange"
        stripe>
        <el-table-column prop="mileage" label="累计里程" align="center" width="110" :key="'mileage'+ active" show-overflow-tooltip sortable='custom'>
            <template slot-scope="scope">{{scope.row.mileage | getMileage}}</template>
        </el-table-column>
        <el-table-column prop="totalTime" label="总时长" align="center" width="100" :key="'totalTime'+ active" show-overflow-tooltip sortable='custom'>
            <template slot-scope="scope">{{scope.row.totalTime | getTimes}}</template>
        </el-table-column>
</el-table>

效果如下,确实比自己写的好看了许多呀。 image.png 点击之后效果如下,完美~~~ image.png

js代码实现

// 列排序
sortChange(column) {
    if(column.order === 'descending'){// 降序
        if(column.prop === 'mileage'){
            this.sort = 1;
        }else {
            this.sort = 3;
        }
    }else {
        if(column.prop === 'mileage'){
            this.sort = 2;
        }else {
            this.sort = 4;
        }
    }
    this.tableData = [];
    this.page.total = 0;
    this.page.pageNum = 1;
    this.getList();
},

好了,以上就是实现elemetui自定义排序了,谢谢阅读,希望对您有帮助!