天天看点

【前端】elementUI分页场景下对表格进行排序

在运用elementUI的table时,在column中加入sortable属性,即可对table进行排序,但排序仅限于单一页面,对分页场景则失效。

以下针对el-table的分页场景进行排序

<el-table
    :data='tableData.slice((page-1)*pageSize, page*pageSize)'
     @sort-change="sortChange"
>
   <el-table-column
           prop='id'
           label='id'
           sortable
   >
   </el-table-column>
   <el-table-column
           prop='Status'
           label='运行状态'
           sortable
   >
 </el-table>
           
// 根据属性值对表格进行排序
 private sortChange(arg: any) {
        if (arg.column) {
            let sortTableData = cloneDeep(this.tableData);
            if (arg.order === 'descending') {
                if (arg.prop === 'id') {
                    sortTableData.sort(this.sortByProp(arg.prop, true));
                } else {
                    sortTableData.sort(this.sortByName(arg.prop, true));
                }
            } else {
                if (arg.prop === 'id') {
                    sortTableData.sort(this.sortByProp(arg.prop, false));
                } else {
                    sortTableData.sort(this.sortByName(arg.prop, false));
                }
            }
            this.tableData = sortTableData;
        } else {
            this.tableData = this.jobListRaw;
        }
        this.page = 1;
    }
    private sortByProp(sortKey: any, order: boolean) {
        if (order) {
            return (a: any, b: any) => {
                return b[sortKey] - a[sortKey];
            };
        } else {
            return (a: any, b: any) => {
                return a[sortKey] - b[sortKey];
            };
        }
    }
    // 根据名称对表格进行排序
    private sortByName(sortKey: any, order: boolean) {
        if (order) {
            return (a: any, b: any) => {
                a[sortKey] = isNull(a[sortKey]) ? '' : a[sortKey];
                b[sortKey] = isNull(b[sortKey]) ? '' : b[sortKey];
                return b[sortKey].localeCompare(a[sortKey]);
            };
        } else {
            return (a: any, b: any) => {
                a[sortKey] = isNull(a[sortKey]) ? '' : a[sortKey];
                b[sortKey] = isNull(b[sortKey]) ? '' : b[sortKey];
                return a[sortKey].localeCompare(b[sortKey]);
            };
        }
    }