问题描述
element表格中的数据有两种形式:数值、字符串。element自带排序方法会发生排序错乱。如图:没有金额时,展示 --
,图中升序排序错乱。
解决步骤
1. 在el-tabel中添加 @sort-change="handleSort"
<el-table
:data="tableData"
class="my-table"
@sort-change="handleSort"
>
</el-table>
2. methods中添加方法
方法中deepCopy
为深拷贝方法,欲了解请点击:https://blog.csdn.net/honeymoon_/article/details/118703712
//自定义表格排序
/**
* 思路:
* 先过滤掉'--'
* 对新数组进行常规升/降序排序,根据传入的order判断是升序还是降序
* 如果点击表头取消排序也需要做判断,将数据还原成接口返回的数据
*/
handleSort({ column, prop, order }) {
//prop:排序的字段、order:升序(ascending)、降序(descending)、取消排序(null)
let copyTableDate = deepCopy(this.tableData); //拷贝表格数据
let reserveData = []; //过滤后保留的数据
let filterData = []; //过滤掉的数据
//开始进行数据过滤:将'--'过滤到filterData数组中,剩余数值型数据保留到reserveData中。
copyTableDate.forEach(item => {
if(item[prop] === '--') { //item[prop]:将要排序那个字段的值
filterData.push(item); //item:表格中的这条数据,即row
} else {
reserveData.push(item);
}
});
// 排序
if (order !== null) {
if (order === 'descending') { //降序
// 冒泡排序
reserveData = reserveData.sort((a, b) => b[prop] - a[prop]);
} else { //升序
reserveData = reserveData.sort((a, b) => a[prop] - b[prop]);
}
// 过滤掉的数据添加到数组末尾
filterData.forEach(item => {
reserveData.push(item);
});
this.tableData = reserveData;
} else {
// 取消排序
//this.copyTable是在接口得到表格数据的时候拷贝了一份,用来还原取消排序时的表格数据
this.tableData = this.copyTable;
}
},
3. 验证
//升序
//降序
//取消排序