前端只排当前页的原因:table bind的data不是完整的dataList,所以排序只排当前页.
<el-table :data="dataList.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize)" .....
解决方法:使用table的sort-change方法前端自己处理。文档:
sort-change | 当表格的排序条件发生变化的时候会触发该事件 | { column, prop, order } |
这里的@sort-change=functioname(info),info是一个参数,包含所排序列的信息-prop和升降顺序-order,console.log(info)打印出来的结果如下:
{column: {…}, prop: "id", order: "descending"}
1.先修改<table的内容
<el-table :data="showed_data" @sort-change="sort_change" ........
2.我们会给完整的dataList排序,所以会改变dataList的值,watch dataList的值,变化时需要改变showed_data值:
watch: {
dataList() {
this.showed_data = this.dataList.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
}
},
3.因为要排序的有很多列,所以写一个通用函数:
sortFun: function (attr, rev) {
//第一个参数传入info里的prop表示排的是哪一列,第二个参数是升还是降排序
if (rev == undefined) {
rev = 1;
} else {
rev = (rev) ? 1 : -1;
}
return function (a, b) {
a = a[attr];
b = b[attr];
if (a < b) {
return rev * -1;
}
if (a > b) {
return rev * 1;
}
return 0;
}
},
4.写@sort-change事件触发的函数:
sort_change(column) {column是个形参,就是前面说的info,你叫什么都可以
console.log(column)
this.currentPage = 1 // return to the first page after sorting
if (column.prop === 'id') {
this.dataList = this.dataList.sort(this.sortFun(column.prop, column.order === 'ascending'));
console.log(this.dataList);
} else if (column.prop === 'status') {
this.dataList = this.dataList.sort(this.sortFun(column.prop, column.order === 'ascending'));
console.log(this.dataList);
}else if (column.prop === 'priority') {
this.dataList = this.dataList.sort(this.sortFun(column.prop, column.order === 'ascending'));
console.log(this.dataList);
}
this.showed_data = this.dataList.slice(0, this.pageSize) // 排序完显示到第一页
console.log('Finished')
console.log(this.showed_data)
}
希望能帮到大家,有什么不明白的或者不对的地方,欢迎评论!!!