Layui 表格全局排序

发布时间 2023-12-13 11:50:19作者: 你说夕阳很美

背景:Layui表格默认是当前页排序,不会全局排序。需要手动修改。

layui分页sort只能当前页不能全局排序解决方案_layui排序-CSDN博客

2021-02-03 layui 数据表格 实现全局排序_layui table 排序-CSDN博客

前端表格

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

首先前端要有排序的设置

table.render(部分)

var inst = table.render({
            elem: '#mantis',
            id: 'mantis',
            url: '',
            toolbar: '#toolbar',
            autoSort: true,
            initSort: {
                field: 'time_consuming'
                , type: 'desc'
            },
            cols: [
                [   // 标题栏
                    {field: 'id', title: '编号', width: 80, sort: true, templet: gen_mantis_url, fixed: 'left'},

事件绑定

table.on('sort(mantis)', function (obj) { //注:tool是工具条事件名,test是table原始容器的属性 lay-filter="对应的值"
            console.log(obj.field); //当前排序的字段名
            console.log(obj.type); //当前排序类型:desc(降序)、asc(升序)、null(空对象,默认排序)
            console.log(this); //当前排序的 th 对象
            table.reload('mantis', {
                initSort: obj //记录初始排序,如果不设的话,将无法标记表头的排序状态。 layui 2.1.1 新增参数
                , where: { //请求参数(注意:这里面的参数可任意定义,并非下面固定的格式)
                    field: obj.field //排序字段   在接口作为参数字段  field order
                    , order: obj.type //排序方式   在接口作为参数字段  field order
                }
            });
        });

后端Flask

@app.get('/api/xxx')
def longTime_not_closed_issues():
    order = request.args.get('order')
    page = request.args.get('page', type=int, default=1)
    per_page = request.args.get('per_page', type=int, default=10)
    q = db.session.query(xxx)
    # print(q)
    bug_id = request.args.get('id')
    if bug_id:
        q = q.where(MantisBugTableORM.id == bug_id)
    if order == 'desc':
        q = q.order_by(desc('time_consuming'))
    elif order == 'asc':
        q = q.order_by(asc('time_consuming'))
    count = len(q.all())
    items = q.limit(per_page).offset((page - 1) * per_page).all()return {
        'code': 0,
        'msg': '信息查询成功',
        'count': count,
        'data': [
            { xxx
            } for item in items
        ]
    }