Element ui全部数据前端排序
1.首先给el-table绑定sort-change监听
<el-table ref="filterTable" :data="historyList.slice((pageNum-1)*pageSize,pageNum*pageSize)" @sort-change="sortChange">
2.给需要排序的列设置sortable属性
<el-table-column label="数据时间" prop="time" sortable='custom'></el-table-column>
3.定义触发排序方法
//排序触发事件
sortChange(column){
this.pageNum = 1
if(column.order === 'ascending'){
this.historyList.sort(this.ascSortFun)
}else if(column.order === 'descending'){
this.historyList.sort(this.desSortFun)
}else{
//取消排序则重新获取列表,恢复默认状态。
this.showHistory()
}
},
column中有两个属性分别是 prop 和 order
当对多个列进行排序时需要通过判断column.prop的值来确定列。
当点击升序按钮时column.order ===“ascending”
点击降序按钮时column.order === ‘descending’
这里还用到了自定义排序方法
//升序排列方法
ascSortFun(a, b) {
//这里直接return a.time-b.time即可
if (a.time > b.time) return 1;
if (a.time == b.time) return 0;
if (a.time < b.time) return -1;
},
//降序排列方法
desSortFun(a,b){
//这里直接return b.time-a.time即可
if (a.time > b.time) return -1;
if (a.time == b.time) return 0;
if (a.time < b.time) return 1;
}
4.多列排序
注意:当多个列排序时为了方便需要先定义一个 存放column.prop的字符串值 的变量。
data() {
return {
historyList: [],
proptype: ""
};
}
在排序触发事件时先判断触发排序的是哪一列
//排序触发事件
sortChange(column){
this.pageNum = 1
if (column.prop === "time") {
this.proptype = column.prop;// 将键名prop赋值给变量proptype
if(column.order === 'ascending'){
this.historyList.sort(this.ascSortFun)
}else if(column.order === 'descending'){
this.historyList.sort(this.desSortFun)
}else{
//取消排序则重新获取列表,恢复默认状态。
this.showHistory()
}
}else if(column.prop === "id"){
this.proptype = column.prop;// 将键名prop赋值给变量proptype
//.....
}
},
这样做的好处是在写排序方法时直接用proptype即可
//升序排列方法
ascSortFun(a, b) {
return a[this.proptype] - b[this.proptype];
},
//降序排列方法
desSortFun(a,b){
return b[this.proptype] - a[this.proptype];
}