欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

layui 树形table分页

程序员文章站 2022-04-29 08:52:52
...

做了伸手党这么久,第一次写博客:

废话不说,这个是根据网上的一个树形表格修改的(出处忘了),(本来没有分页的,还有点击事件不是我想要的),所以修改了

弊端:分页后其剩下的孩子没有属于父,看图layui 树形table分页

layui 树形table分页系统管理下有四个孩子,分页后,每页3条,第二页只有剩下的,没有树形效果了,因为第二页没有系统管理这一条数据,如果想显示只能系统管理这一条数据它出来

接下来贴代码(由于上面的涉及逻辑代码多,我贴下面的)layui 树形table分页

 

<div class="layadmin-tabsbody-item layui-show">
    <div class="layui-fluid">
        <div class="layui-row layui-col-space15" style="width: 28%;float: left">
            <div class="layui-card">
                <div class="layui-card-body">
                    <div class="layui-layout">
<!--                        <div class="div-head">-->
<!--                            <div class="div-inline div-center" style="left: 4%"><p class="div-inline">角色管理</p></div>-->
<!--                            <div class="div-inline div-center" style="left: 97%">-->
<!--                                <button id="addJob" type="button" href="javascript:void(0)" class="layui-btn layui-btn-sm layui-btn-radius layui-btn-primary">添加</button>-->
<!--                            </div>-->
<!--                        </div>-->
                        <div class="layui-table-box" style="overflow:auto;height:89%;">
                            <table id="roleTable" class="layui-table" style="display: none" lay-filter="roleTable"></table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-row layui-col-space15" style="width: 48%;float: left;margin-left: 10px">
            <div class="layui-card">
                <div class="layui-card-body">
                    <div class="layui-layout">
                        <!--                        <div class="div-head">-->
                        <!--                            <div class="div-inline div-center" style="left: 4%"><p class="div-inline">角色管理</p></div>-->
                        <!--                            <div class="div-inline div-center" style="left: 97%">-->
                        <!--                                <button id="addJob" type="button" href="javascript:void(0)" class="layui-btn layui-btn-sm layui-btn-radius layui-btn-primary">添加</button>-->
                        <!--                            </div>-->
                        <!--                        </div>-->
                        <div class="layui-table-box" style="overflow:auto;height:89%;">
                            <table id="roleMenuTable" class="layui-table" style="display: none" lay-filter="roleMenuTable"></table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script data-th-inline="none" type="text/javascript">
    layui.config({
        base: './layui/'
    }).extend({
        treetable: 'lay/modules/treetable-lay/treetable'
    }).use(['table','layer','form','element','treetable'], function(){
        var table = layui.table;
        var layer = layui.layer;
        var form = layui.form;
        var element = layui.element;
        var treetable = layui.treetable;
        layer.load(2);
        // 渲染表格
        var renderTable = function (elem,url,data) {
            table.render({
                elem: elem
                , url: url
                , cols: [[
                    {type:'radio'},
                    {field: 'roleName', title: '角色名称'}
                ]]
                , page: true
                , limit: 10   //默认十条数据一页
                , limits: [10, 20, 30, 50]  //数据分页条
                , where :data
                , done: function (res, curr, count) {
                    layer.closeAll('loading');
                    layer.msg(res.msg);
                    res.data[0]["LAY_CHECKED"]='true';  //数据添加选中
                    //下面是通过更改css来实现选中的效果
                    var index= res.data[0]['LAY_TABLE_INDEX'];
                    var dom = $('tr[data-index=' + index + '] input[type="radio"]');
                    dom.prop('checked', true);
                    dom.next().addClass('layui-form-checked layui-form-radioed');
                    dom.next().find('i').addClass('layui-anim-scaleSpring');
                    form.render('radio');   //渲染
                    var data= {'roleId':res.data[0]["id"],'asc':'sort'};
                    renderMenuTable(data);    //加载table菜单数据
                }, parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
                    return {
                        "code": res.code, //解析接口状态
                        "msg": res.message, //解析提示文本
                        "count": res.count, //解析数据长度
                        "data": res.data //解析数据列表
                    };
                }
            });
        };
        renderTable('#roleTable','/role/getRolePage');
        // var oldData =  table.cache["roleTable"];
        // console.log(oldData);
        table.on('radio(roleTable)',function (obj) {
            var data= {'roleId':obj.data.id,'asc':'sort'};
            //点击单选加载菜单
            renderMenuTable(data);
        });
        table.on('checkbox(roleMenuTable)',function (obj) {
            // var data= {'roleId':obj.data.id};
            // renderTable('#roleMenuTable','/menu/getMenuPage',menuColArray,{'data':data});
            console.log(obj);
            getCheckData();
        });
        function renderMenuTable(data) {
            layer.load(2);
            treetable.render({
                treeColIndex: 1,//树形图标显示在第几列
                treeSpid: 0,//最上级的父级id
                treeIdName: 'menuId',//id字段的名称
                treePidName: 'pid',//pid字段的名称
                treeDefaultClose: false,//是否默认折叠
                treeLinkage: true,//父级展开时是否自动展开所有子级
                even:false,  //开启间隔行变色
                elem: '#roleMenuTable',
                url: '/menu/getMenuPage',
                page: true,
                limit: 1,   //默认十条数据一页
                limits: [10, 20, 30, 50],  //数据分页条
                where :data,
                cols: [[
                    {type:'checkbox'},
                    {field: 'menuName', title: '菜单名称'}
                ]],
                done: function () {
                    layer.closeAll('loading');
                }
            });
        }
        function getCheckData(){ //获取选中数据

            var checkStatus = table.checkStatus('roleMenuTable') //id
                , data = checkStatus.data;
            console.log(data)
        }
    });
</script>
@ResponseBody
    @RequestMapping("/getMenuPage")
    public SystemResponse getJobPage(Page page){
        try {
            Map map =  menuServiceImpl.findListByPage(page);
            return new SystemResponse().pageData(map.get("count"),map.get("data"));
        }catch (Exception e){
            return new SystemResponse().pageDataFail();
        }
    }
@Override
    public Map findListByPage(Page page) {
        return personMenuViewDao.findListByPage(page);
    }
@Getter
@Setter
public class Page implements Serializable {
    private static final long serialVersionUID = -5601574509801101671L;
    private Integer limit;
    private Integer page;
    private JSONObject data;
}

 

接下来是dao

public Map findListByPage(Page page){
        final String[] sql = {MessageFormat.format("FROM {0} ", entityClass.getSimpleName())};
        JSONObject jsonObject = page.getData();
        HashMap hashMap = new HashMap();
        if(jsonObject!=null) {
            for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
                if(entry.getKey().equals("desc")||entry.getKey().equals("asc")){
                    hashMap.put(entry.getKey(),entry.getValue());
                }else if(sql[0].contains("where")){
                        sql[0] += " and " + entry.getKey() + "= '" + entry.getValue() + "'";
                }else {
                        sql[0] += " where " + entry.getKey() + "= '" + entry.getValue() + "'";
                    }
                }
            hashMap.forEach((k,v) -> {
                sql[0] += " order by "+v+" "+k;
            });
        }
        Query queryCount = createHSQL("SELECT COUNT(*) FROM "+entityClass.getSimpleName());
        Object num = queryCount.getSingleResult();
        Query query = createHSQL(sql[0]);
        if(page.getLimit()!=null&page.getPage()!=null) {
            query.setFirstResult((page.getPage() - 1) * page.getLimit());
            query.setMaxResults(page.getLimit());
        }
        List<T> list = getHSQLList(query);
        entityManager.close();
        Map map = new HashMap();
        map.put("count",num);
        map.put("data",list);
        return map;
    }

也贴一下SystemResponse

public class SystemResponse extends JSONObject {
    private static final long serialVersionUID = -4779671740130436649L;
    public SystemResponse code(String code) {
        this.put("code", code);
        return this;
    }

    public SystemResponse message(String message) {
        this.put("message", message);
        return this;
    }

    public SystemResponse data(Object data) {
        this.put("data", data);
        return this;
    }

    public SystemResponse count(Object count) {
        this.put("count", count);
        return this;
    }
    public SystemResponse success() {
        this.code("success");
        return this;
    }

    public SystemResponse fail() {
        this.code("fail");
        return this;
    }

    public SystemResponse error() {
        this.message("系统错误");
        return this;
    }
    public SystemResponse pageData(Object count,Object data) {
        this.code("0");
        this.message("success");
        this.count(count);
        this.data(data);
        return this;
    }
    public SystemResponse pageDataFail() {
        this.code("1");
        this.message("系统错误");
        this.count("0");
        this.data(new ArrayList<>());
        return this;
    }
}

最后treetable给百度云算了

layui.define(['layer', 'table'], function (exports) {
    var $ = layui.jquery;
    var layer = layui.layer;
    var table = layui.table;
    var treetable = {
        // 渲染树形表格
        render: function (param) {
            // 检查参数
            if (!treetable.checkParam(param)) {
                return;
            }
            // 获取数据
            if (param.data) {
                treetable.init(param, param.data);
            } else {
                if(param.page){
                    var page = {'page':'1','limit':param.limits[0],'data':param.where};
                    $.post(param.url,page,function (res) {
                        treetable.init(param, res);
                    })
                }else {
                    $.getJSON(param.url, param.where, function (res) {
                        treetable.init(param, res);
                    });
                }
            }
        },
        // 渲染表格
        init: function (param, data) {
            var mData = [];
            var doneCallback = param.done;
            var tNodes = data.data;
            // 补上id和pid字段
            for (var i = 0; i < tNodes.length; i++) {
                var tt = tNodes[i];
               // tt.id = tt[param.treeIdName];
                if (!tt.id) {
                    if (!param.treeIdName) {
                        layer.msg('参数treeIdName不能为空', {icon: 5});
                        return;
                    }
                    tt.id = tt[param.treeIdName]
                }
                if (!tt.pid) {
                    if (!param.treePidName) {
                        layer.msg('参数treePidName不能为空', {icon: 5});
                        return;
                    }
                    tt.pid = tt[param.treePidName];
                }
            }
            // 对数据进行排序
            var sort = function (s_pid, data) {
                for (var i = 0; i < data.length; i++) {
                    if (data[i].pid == s_pid) {
                        var len = mData.length;
                        if (len > 0 && mData[len - 1].menuId == s_pid) {
                            mData[len - 1].isParent = true;
                        }
                        mData.push(data[i]);
                        sort(data[i].menuId, data);
                    }
                }
            };
            sort(param.treeSpid, tNodes);

            // 重写参数
            param.url = undefined;
            param.data = mData;
            param.cols[0][param.treeColIndex].templet = function (d) {
                var mId = d.menuId;
                var mPid = d.pid;
                var isDir = d.isParent;
                var emptyNum = treetable.getEmptyNum(mPid, mData);
                var iconHtml = '';
                for (var i = 0; i < emptyNum; i++) {
                    iconHtml += '<span class="treeTable-empty"></span>';
                }
                if (isDir) {
                    //父层
                    iconHtml += '<i class="layui-icon layui-icon-triangle-d"></i> <i class="layui-icon"></i>';
                } else {
                    //子层
                    iconHtml += '<i class="layui-icon "></i>';
                }
                iconHtml += '&nbsp;&nbsp;';
                var celType = isDir ? 'dir' : 'file';
                var vg = '<span class="treeTable-icon open" lay-tid="' + mId + '" lay-cel-pid="' + mPid + '" lay-cel-type="' + celType + '">';
                return vg + iconHtml + d[param.cols[0][param.treeColIndex].field] + '</span>'
            };

            param.done = function (res, curr, count) {
                $(param.elem).next().addClass('treeTable');
                //$('.treeTable .layui-table-page').css('display', 'none');
                $(param.elem).next().attr('treeLinkage', param.treeLinkage);
                if (param.treeDefaultClose) {
                    treetable.foldAll(param.elem);
                }
                if (doneCallback) {
                    doneCallback(res, curr, count);
                }
            };
            // 渲染表格
            table.render(param);
        },

        // 计算缩进的数量
        getEmptyNum: function (pid, data) {
            var num = 0;
            if (!pid) {
                return num;
            }
            var tPid;
            for (var i = 0; i < data.length; i++) {
                if (pid == data[i].menuId) {
                    num += 1;
                    tPid = data[i].pid;
                    break;
                }
            }
            var number = treetable.getEmptyNum(tPid, data);
            return num + number;
        },

        // 检查参数
        checkParam: function (param) {
            if (!param.treeSpid && param.treeSpid != 0) {
                layer.msg('参数treeSpid不能为空', {icon: 5});
                return false;
            }

            if (!param.treeColIndex && param.treeColIndex != 0) {
                layer.msg('参数treeColIndex不能为空', {icon: 5});
                return false;
            }
            return true;
        },
        // 展开所有
        expandAll: function (dom) {
            $(dom).next('.treeTable').find('.layui-table-body tbody tr').each(function () {
                var $ti = $(this).find('.treeTable-icon');
                var celType = $ti.attr('lay-cel-type');
                var tOpen = $ti.hasClass('open');
                if ('dir' === celType && !tOpen) {
                    $ti.trigger('click');
                }
            });
        },
        // 折叠所有
        foldAll: function (dom) {
            $(dom).next('.treeTable').find('.layui-table-body tbody tr').each(function () {
                var $ti = $(this).find('.treeTable-icon');
                var celType = $ti.attr('lay-cel-type');
                var tOpen = $ti.hasClass('open');
                if ('dir' === celType && tOpen) {
                    $ti.trigger('click');
                }
            });
        },
        // 点击单元格展开/折叠行
        cellToggleRows: function ($dom, linkage) {
            var type = $dom.attr('lay-cel-type');
            if ('file' === type) return;
            var mId = $dom.attr('lay-tid');
            var isOpen = $dom.hasClass('open');
            if (isOpen)  $dom.removeClass('open');
            else $dom.addClass('open');
            $dom.closest('tbody').find('tr').each(function () {
                var $ti = $(this).find('.treeTable-icon');
                var pid = $ti.attr('lay-cel-pid');
                var celType = $ti.attr('lay-cel-type');
                var tOpen = $ti.hasClass('open');
                if (mId === pid) {
                    if (isOpen) {
                        $(this).hide();
                        if ('dir' === celType && tOpen === isOpen)
                            treetable.cellToggleRows($ti, true);
                    }else {
                        $(this).show();
                        if (linkage && 'dir' === celType && tOpen === isOpen)
                            treetable.cellToggleRows($ti,true);
                    }
                }
            });
        },
        // 点击图标展开/折叠行
        // toggleRows: function ($dom, linkage) {
        //     var type = $dom.attr('lay-cel-type');
        //     if ('file' === type) {
        //         return;
        //     }
        //     var mId = $dom.attr('lay-tid');
        //     var isOpen = $dom.hasClass('open');
        //     if (isOpen) {
        //         $dom.removeClass('open');
        //     } else {
        //         $dom.addClass('open');
        //     }
        //     $dom.closest('tbody').find('tr').each(function () {
        //         var $ti = $(this).find('.treeTable-icon');
        //         var pid = $ti.attr('lay-cel-pid');
        //         var celType = $ti.attr('lay-cel-type');
        //         var tOpen = $ti.hasClass('open');
        //         if (mId === pid) {
        //             if (isOpen) {
        //                 $(this).hide();
        //                 if ('dir' === celType && tOpen === isOpen) {
        //                     $ti.trigger('click');
        //                 }
        //             } else {
        //                 $(this).show();
        //                 if (linkage && 'dir' === celType && tOpen === isOpen) {
        //                     $ti.trigger('click');
        //                 }
        //             }
        //         }
        //     });
        // }
    };

    layui.link(layui.cache.base + 'lay/modules/treetable-lay/treetable.css');

    //给单元格列绑定事件
    $('body').on('click', '.treeTable .layui-table-cell', function () {
        var treeLinkage = $(this).parents('.treeTable').attr('treeLinkage');
        if ('true' === treeLinkage) {
            treetable.cellToggleRows($(this).find('.treeTable-icon'), true);
        } else {
            treetable.cellToggleRows($(this).find('.treeTable-icon'), false);
        }
    });

    // 给图标列绑定事件 (给单元格列绑定事件不可共存);
    // $('body').on('click', '.treeTable .treeTable-icon', function () {
    //     var treeLinkage = $(this).parents('.treeTable').attr('treeLinkage');
    //     if ('true' == treeLinkage) {
    //         treetable.toggleRows($(this), true);
    //     } else {
    //         treetable.toggleRows($(this), false);
    //     }
    // });
    exports('treetable', treetable);
});

链接: https://pan.baidu.com/s/1PTCN1jk2blwFmJ1ud_Aw6g&shfl=shareset 提取码: imfj 

相关标签: layui table