背景
由于最近工作在写前端,增加了对列进行排序的需求,去官网学习了bootstrap-table的Multiple Sort,贴上链接Bootstrap Table Examples
这里不得不吐槽一下官网,放出来demo,不贴源码。。。
实现步骤
单列排序
1.先引入jquery和bootstrap-table的插件,
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/jquery/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap-table-zh-CN.min.js}" ></script>
2.在渲染table时,增加这三个属性
$('#table').bootstrapTable({
pagination: true,
sidePagination: "server",
sortable:true
...
// 也可以把sortable:true加在单独需要排序的列上,
columns: [{
field: "id",
title: "编号",
width: "60",
sortable:true
}
});
此处需注意,虽然sidePagination标识在服务器端分页或客户端分页,但若不加该属性,排序无法生效。
多重排序
1.本次需求还涉及到多重排序,需要引入插件
<script th:src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap-table-multiple-sort.js}"></script>
2.增加属性
$('#table').bootstrapTable({
pagination: true,
sidePagination: "server",
url: ...,
queryParams: function (params) {
// 此处对排序字段和方式做处理,因为默认的是多个排序字段会分开传入给后台,我需要把多个字段和多个方式同时传入
if(null != params.multiSort && undefined != params.multiSort){
params.sort = params.multiSort.map(item => {
return item.sortName;
}).join(',');
params.order = params.multiSort.map(item => {
return item.sortOrder;
}).join(',');
params.multiSort = null;
}
return params;
},
sortable: true, // 是否启用排序
showMultiSort: true, // 多列排序
....
});
sort:id,name,age
order:asc,desc,asc
后台设计
// 接口
@PostMapping("/test")
public List<Map> test(PageParam pageParam,
@RequestParam(value = "sort",required = false) String sort,
@RequestParam(value = "order",required = false) String order) {
// TODO
}
//service
@Override
public Map getSortMap(String sort, String order) {
log.info("开始创建排序Map,sort:{},order:{}",sort,order);
Map<String,String> sortMap = new HashMap();
String[] keys = sort.split(",");
String[] values = order.split(",");
for (int i = 0; i < keys.length; i++) {
sortMap.put(keys[i],values[i]);
}
log.info("完成创建排序Map");
return sortMap;
}
//mapper
select * from test
<where>
<choose>
<when test="sortInfo!=null and sortInfo !=''">
order by ${sortInfo}
</when>
<otherwise>
order by id desc
</otherwise>
</choose>
</where>
附上官网效果