QQ交流群:110826636

分享layui的table的一些小技巧,前端分页

最近一直在折腾报表,期间使用了layui的table做展示(版本号:2.5.5)

起初:以为是查询结果出来后,前端和服务端分页一弄就完事了,参考例子,但是sql写得太长太长了,翻页困难,数据库是老旧的SqlServer2008 R2

接着:开始改造,由于查询出来的数据量不是很大,约在10w以内,于是开始【一次请求,前端自己分页】的思路,浏览器还是很强大的

$.ajax({
                type: "post",
                url: "请求地址", 
                async: true,
                data: {
                    //查询条件
                },
                success: function (res) {
                    sourceData = res.data;
                    pageData = res.data;
                    let new_data = $.extend(true, [], res.data);
                    tableIns=table.render({
                        elem: '#dataTable'
                        , id: 'dataTable'
                        , height: height
                        , loading: true
                        , title: tbTitle
                        , autoSort: false //手动排序
                        , page: true
                        , limit: m_limit
                        , limits:[50,100,200,300]
                        , toolbar: '#toolbar'
                        , defaultToolbar: ['filter', 'print']
                        , cols: [[
                        { field: '序号', title: '序号', width: 70, fixed: 'left', type: 'numbers' }
                        //需要显示的列
                            ]]
                        , data:new_data
                        , done: function () {
                            searchPage();
                        }
                    });
                }
            })

利用table的data属性进行数据的赋值,完成前端的分页。拉了生产大概八九万的数据测试展示,没有卡顿,(本机8G内存,i5 4核,普通用户机器4G)

之后:因为还想提供前端的本地搜索功能,完善了searchPage()函数,随意使用一个输入框

        function searchPage() {
            $("#Keyword").keydown(function (e) {
                var curKey = e.which;
                if (curKey == 13) {
                    var loading = layer.load(2, {
                        content:'搜索中...',
                        shade:  [0.3, '#393D49'],time: 3 * 1000
                    });
                    var Keyword = $('#Keyword').val();
                     Keyword = trim(Keyword);
                    pageData = array_search(sourceData, Keyword);
                    let new_data = $.extend(true, [], pageData);    
                    table.reload('dataTable', { data: new_data });
                    layer.close(loading);
                    $('#Keyword').val(Keyword);
                }
            });
        }

 核心搜索函数array_search(),查找匹配的数据

/*
* js array_searcy() 函数
* @param array 必选参数 要查找的数组或对象
* @param find 必须参数 要查找的内容
*/
function array_search(array, str) {
    if (typeof array !== 'object') {
        return false;
    } else {
        var found = [];
        for (var i = 0; i < array.length; i++) {
            for (var j in array[i]) {
                var value = array[i][j]+'';//转化为字符串
                if (value.indexOf(str) >= 0) {
                    found.push(array[i]);
                    break;
                }
            }
        }
        return found;
    }
}
//去左空格;
function ltrim(s) {
    return s.replace(/(^\s*)/g, "");
}
//去右空格;
function rtrim(s) {
    return s.replace(/(\s*$)/g, "");
}
//去左右空格;
function trim(s) {
    return s.replace(/(^\s*)|(\s*$)/g, "");
}

 小细节扩展:如果想excel导出可以使用前端导出,但是数据量大的时候,会卡死浏览器,无法异步(也考虑使用woker对象,但还是不好弄,一些信息和组件无法在woker里面使用)

后续:增加了一个前端排序,自带的排序autoSort需要关闭(原排序只针对当前页排序,适合后端前端联动排序)

        table.on('sort(dataTable)', function (obj) {
            //console.log(obj.field); //当前排序的字段名
            //console.log(obj.type); //当前排序类型:desc(降序)、asc(升序)、null(空对象,默认排序)
            let sortSourceData = $.extend(true, [], sourceData);
            let sortType = "";
            switch (obj.field) {
                case '需要排序的字段'://需注意在field绑定的时候开启sort
                    sortType = "number"; break;
            }
            tableSort(sortSourceData, obj.field, obj.type, sortType);
            //console.log(sortSourceData);
            //console.log(sourceData);
            table.reload('dataTable', {
              initSort: obj //记录初始排序,如果不设的话,将无法标记表头的排序状态。
              ,where: { //请求参数(注意:这里面的参数可任意定义,并非下面固定的格式)
                field: obj.field //排序字段
                ,order: obj.type //排序方式
              },data: sortSourceData
            });
        });

 核心函数tableSort(),利用array自带的sort进行扩展

//asc 升序
//desc 降序
/**
 * @tableObj 表
 * @field 字段
 * @orderBy 排序方式
 * @sortType 排序是类型
 */
function tableSort(tableObj, field, orderBy, sortType) {
    var type = 'number';
    if (sortType == null && tableObj.length > 0) {
        type = typeof(tableObj[0][field]);
    } else {
        type = sortType;
    }
    if (orderBy == 'desc') {
        return tableObj.sort(function (a, b) {
            var x = a[field];
            var y = b[field];
            switch (type) {
                case 'number':
                    if (x == null) {
                        x = 0;
                    }
                    if (y == null) {
                        y = 0;
                    }
                    return x - y;
                case 'string':
                    if (x == null || x == '') {
                        x = 0;
                    } else {
                        x = x.charCodeAt(0);
                    }
                    if (y == null || y == '') {
                        y = 0;
                    } else {
                        y = y.charCodeAt(0);
                    }
                    return x- y;
                case 'datetime':
                    if (x == null) {
                        x = 0;
                    } else {
                        x = new Date(x).getTime();
                    }
                    if (y == null) {
                        y = 0;
                    } else {
                        y = new Date(y).getTime();
                    }
                    return x - y;
            }
        });
    } else if (orderBy == 'asc') {
        return tableObj.sort(function (a, b) {
            var x = a[field];
            var y = b[field];
            switch (type) {
                case 'number':
                    if (x == null) {
                        x = 0;
                    }
                    if (y == null) {
                        y = 0;
                    }
                    return y - x;
                case 'string':
                    if (x == null || x == '') {
                        x = 0;
                    } else {
                        x = x.charCodeAt(0);
                    }
                    if (y == null || y == '') {
                        y = 0;
                    } else {
                        y = y.charCodeAt(0);
                    }
                    return y - x;
                case 'datetime':
                    if (x == null) {
                        x = 0;
                    } else {
                        x = new Date(x).getTime();
                    }
                    if (y == null) {
                        y = 0;
                    } else {
                        y = new Date(y).getTime();
                    }
                    return y - x;
            }
        });
    }
}

 

posted @ 2020-04-14 11:02  FourOne  阅读(1961)  评论(0编辑  收藏  举报