Loading... # ElementUI Table组件 自定义排序相关 ## sort-method ```html <el-table :data="tableData" :header-cell-style="rowStyle" :cell-style="rowStyle" border style="width: 100%"> <!-- sortable还可写成:sortable=true --> <el-table-column prop="courseShowDate" label="日期" sortable :sort-method="compare"></el-table-column> </el-table> ``` ```js // methods{ // 入参是两个对象,可通过console.log打印查看 compare(obj1, obj2) { // 我这里需要让日期升降序,所以这样写 let o1 = obj1.courseShowDate; let o2 = obj2.courseShowDate; if (o1 === "Monday") o1 = 1; if (o2 === "Monday") o2 = 1; if (o1 === "Tuesday") o1 = 2; if (o2 === "Tuesday") o2 = 2; if (o1 === "Wednesday") o1 = 3; if (o2 === "Wednesday") o2 = 3; if (o1 === "Thursday") o1 = 4; if (o2 === "Thursday") o2 = 4; if (o1 === "Friday") o1 = 5; if (o2 === "Friday") o2 = 5; if (o1 === "Saturday") o1 = 6; if (o2 === "Saturday") o2 = 6; if (o1 === "Sunday") o1 = 7; if (o2 === "Sunday") o2 = 7; // 这里和Java的sort一样 return o1 - o2; } ``` ## sort-change ```html <!-- @sort-change="onSortChange" --> <el-table :data="tableData" :header-cell-style="rowStyle" :cell-style="rowStyle" border @sort-change="onSortChange" style="width: 100%"> <!-- sortable="custom" :sort-orders="['ascending','descending']"--> <el-table-column prop="courseShowDate" label="日期" sortable="custom" :sort-orders="['ascending','descending']"></el-table-column> </el-table> ``` ```js /** * 表格排序事件处理函数 * @param {object} {column,prop,order} 列数据|排序字段|排序方式 */ onSortChange({ prop, order }) { this.tableData.sort(this.compare(prop, order)); }, /** * 排序比较 * @param {string} courseShowDate 排序的属性名 * @param {string} sort ascending(升序)/descending(降序) * @return {function} */ compare (courseShowDate, sort) { return function (obj1, obj2) { let o1 = obj1[courseShowDate]; let o2 = obj2[courseShowDate]; if (o1 === "Monday") o1 = 1; if (o2 === "Monday") o2 = 1; if (o1 === "Tuesday") o1 = 2; if (o2 === "Tuesday") o2 = 2; if (o1 === "Wednesday") o1 = 3; if (o2 === "Wednesday") o2 = 3; if (o1 === "Thursday") o1 = 4; if (o2 === "Thursday") o2 = 4; if (o1 === "Friday") o1 = 5; if (o2 === "Friday") o2 = 5; if (o1 === "Saturday") o1 = 6; if (o2 === "Saturday") o2 = 6; if (o1 === "Sunday") o1 = 7; if (o2 === "Sunday") o2 = 7; if (o1 <= o2) { return sort === 'ascending' ? -1 : 1 } else if (o1 > o2) { return sort === 'ascending' ? 1 : -1 } } } ``` 参考: 1. [官方文档](https://element.eleme.cn/#/zh-CN/component/table) 2. [夜无明月-element-ui中表格自定义排序](https://www.cnblogs.com/snaillu/p/14150536.html) 最后修改:2022 年 10 月 03 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 本作品采用 CC BY-NC-SA 4.0 International License 进行许可。