盛世宏图 发表于 2024-11-22 21:32:58

Layui数据表格开启前端排序切换功能实现Demo

备注


[*]分页一般环境下必须得增加排序条件,不然排序可能会出现问题
[*]采用的前端框架是Layui、后端是SpringBoot、Mybatis、数据库是PostgreSQL
[*]pgsql排序需注意null值
-- 表示null排在有值行的前面
select * from tbl order by id nulls first;
-- 表示null排在有值行的后面
select * from tbl order by id nulls last;
Layui表格根据对应字段举行切换排序

Layui数据表格官网地址
重要是通过针对Layui表格table的cols列表渲染中的sort属性,以及表格监听sort事件举行实现,后端根据前台通报过来的排序属性和分列方式举行动态切换数据表格的排序方式。
参考官方文档

1. 表格sort事件

https://i-blog.csdnimg.cn/direct/ac2825ba7b3b4e258b48da121ef02143.png
表格列表选项渲染

https://i-blog.csdnimg.cn/direct/b7759ec2ad894a6da251cb5b9469c1fd.png
代码实战

1、前端页面代码渲染

HTML

<table class="layui-hide" id="table" lay-filter="table"></table>
js

//获取本服务对应地址
let domainName = window.location.origin;
layui.use(['form', 'table', 'util', 'upload', 'laydate','xmSelect'], function (
   //表格渲染
   Common.layTablePageRender({
            elem: '#table',
            url: "/guide/core/list",
            page: true,
            limit: 10,
            tableId: 'tableId',
            height: "full-255",
            toolbar: '#toolBar',
            autoSort: false,
            cols: [[
                {type: 'checkbox', fixed: 'left'},
                {field: 'name', align: 'center', title: '标题', minWidth: 250},
                //sort开启上线时间日期渲染
                {field: 'declareTime', align: 'center', title: '上线日期', minWidth: 100,sort:true},
                {field: 'createBy', align: 'center', title: '创建人', minWidth: 100},
                {
                  field: 'recentOperate',
                  align: 'center',
                  title: '最近一次操作',
                  minWidth: 100,
                  templet: function (row) {
                        if (row.updateBy) {
                            return `${row.updateBy}于${row.updateTime}修改`;
                        }
                        return '';
                  }
                }
            ]]
      })
      
      //监听表格排序事件
      table.on('sort(table)', function (obj) { //注:tool 是工具条事件名,test 是 table 原始容器的属性 lay-filter="对应的值"
         // obj为表格排序数据
          console.log(obj.field); // 当前排序的字段名
                  console.log(obj.type); // 当前排序类型:desc(降序)、asc(升序)、null(空对象,默认排序)
                  console.log(this); // 当前排序的 th 对象

                  // 尽管我们的 table 自带排序功能,但并没有请求服务端。
                  // 有些时候,你可能需要根据当前排序的字段,重新向后端发送请求,从而实现服务端排序,如:
         let field = {};
         field.sortType = obj.type;
         field.sortField = obj.field == 'declareTime' ? 'declare_time' : obj.field;
         
         table.reload('tableId', {
                page:{
                  curr:1
                },
                where: field
            })
      });
         
));
//封装的layui表格渲染方法,针对的是若依框架的分页数据渲染方式
Common.layTablePageRender= function ({elem,url,page,toolbar,limit,tableId,height,cols,where}){
    if (!page) page = true
    if (!limit) limit = 10
    layui.table.render({
      elem: elem,
      url: domainName + url,
      headers: {"Authorization": 'Bearer ' + localStorage.getItem("access_token")},
      request: {
            pageName: 'pageNum' //页码的参数名称,默认:page
            , limitName: 'pageSize' //每页数据量的参数名,默认:limit
      },
      toolbar:toolbar,
      page: page,
      limit: limit,
      id: tableId,
      height,
      cols: cols
      , parseData: function (res) { //res 即为原始返回的数据
            if (res.code == messageState.success) {
                return {
                  "code": 0, //解析接口状态 0-正确码
                  "msg": res.msg, //解析提示文本
                  "count": res.total, //解析数据长度
                  "data": res.rows //解析数据列表
                };
            } else if (res.code == messageState.fail) {
                myLayer.Alert('加载失败!');
                return false;
            } else {
                myLayer.Alert(res.msg, function () {
                  messageState.timeoutToLogin();
                });
                return false;
            }
      },where:where
    });
}
后台代码

//controller
           /**
   * 查询指南列表
   */
    @PreAuthorize("@ss.hasPermi('guide:core:list')")
    @ApiOperation("查询列表")
    @GetMapping("/list")
    public TableDataInfo list(Integer pageNum,Integer pageSize,String sortField,String sortType) {
      //开启分页
      PageHelper.startPage(pageNum, pageSize);
      List<BackGuideCoreDetailVo> list = guideCoreService.selectList(sortField,sortType);
      return getDataTable(list);
    }
    //service
    List<BackGuideCoreDetailVo> selectList(sortField,sortType);
    //service实现类
   @Override
    public List<BackGuideCoreDetailVo> selectList(sortField,sortType) {
      List<BackGuideCoreDetailVo> list = guideCoreMapper.selectList(sortField,sortType);
      return list;
    }
    //mapper接口
    List<BackGuideCoreDetailVo> selectList(@Param("sortField") String sortField, @Param("sortType") String sortType);           
xml

   <select id="selectList" resultMap="BackGuideCoreDetailVo">
                select *
      from com_user a
                -- 存在需要排序的字段
      <if test="sortField!='' and sortField != null">
            order by a.${sortField} ${sortType}
      </if>
      -- 默认排序
      <if test="sortField == null">
            order by a.update_time desc nulls last,create_time desc
      </if>
    </select>

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: Layui数据表格开启前端排序切换功能实现Demo