首頁 >web前端 >Layui教程 >layui實作資料表格及分頁的方法

layui實作資料表格及分頁的方法

尚
轉載
2020-06-11 17:25:424960瀏覽

layui實作資料表格及分頁的方法

一.前端部分

html只需要放一個有id的div就行了,方便js取得渲染區域

<div id="data_grid" lay-filter="demo" ></div>  

js部分要注意url為非同步資料介面,done是渲染表格之後的回呼函數

table.render({
            elem: &#39;#data_grid&#39;
            //,width: 900
            //,height: 274
            ,cols: [[ //标题栏
                {field: &#39;id&#39;, title: &#39;ID&#39;, width: 80, sort: true}
                ,{field: &#39;username&#39;, title:&#39;用户名&#39;,width: 100} //空列
                ,{field: &#39;password&#39;, title: &#39;密码&#39;, width: 120}
                ,{field: &#39;gender&#39;, title: &#39;性别&#39;, width: 150}
                ,{field: &#39;nichen&#39;, title: &#39;昵称&#39;, width: 150}
                ,{field: &#39;birthday&#39;, title: &#39;出生年月&#39;, width: 120}
                ,{fixed: &#39;right&#39;, width: 215,align:&#39;center&#39;, toolbar: &#39;#barDemo&#39;}
            ]]
            ,url:url
            ,skin: &#39;row&#39; //表格风格
            ,even: true
            ,page: true //是否显示分页
            ,limits: [3,5,10]
            ,limit: 5 //每页默认显示的数量
            ,done:function(res){
                userPage.data = res.data;
            }
            //,loading: false //请求数据时,是否显示loading
        }); 

根據條件查詢,表格非同步刷新,where為附帶參數

$(&#39;#sub_query_form&#39;).on(&#39;click&#39;,function () {
        var queryPo = page.formToJson($(&#39;#query_form&#39;).serialize());
        var table = layui.table;
        table.reload(&#39;data_grid&#39;, {
            url: &#39;/getUserList.action&#39;,
            page:{
                curr:1  //从第一页开始
            },

            method:&#39;post&#39;,
            where:{
                queryStr:queryPo
            },
            done:function (res) {
                userPage.data = res.data;
            }
        });
    }); 

將x-www-form-urlencoded轉化為json字串

formToJson:function (data) {
        data=data.replace(/&/g,"\",\"");
        data=data.replace(/=/g,"\":\"");
        data="{\""+data+"\"}";
        return data;
    }

表格工具列使用

1.首先在html裡定義好按鈕

<script type="text/html" id="barDemo">
        <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="add">增加</a>
        <a class="layui-btn layui-btn-xs" lay-event="detail">查看</a>
        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>

        <!-- 这里同样支持 laytpl 语法,如: -->
        {{#  if(d.auth > 2){ }}
        <a class="layui-btn layui-btn-xs" lay-event="check">审核</a>
        {{#  } }}
</script>

2.js內引用

layui.use(&#39;table&#39;, function(){
    var table = layui.table;
    userPage.tab(&#39;/getUserList.action&#39;);
    //监听工具条
    table.on(&#39;tool(demo)&#39;, function(obj){
        var data = obj.data;
        userPage.data = obj.data;
        if(obj.event === &#39;detail&#39;){
            layer.msg(&#39;ID:&#39;+ data.id + &#39; 的查看操作&#39;);
        }
        else if(obj.event === &#39;del&#39;){
            layer.confirm(&#39;真的要删除这条记录么&#39;,{icon: 3, title:&#39;确定删除&#39;}, function(index){
                obj.del();
                $.post(&#39;/doDelete.action?id=&#39;+data.id,function (res) {
                    userPage.reload(res);
                });
                layer.close(index);
            });

        }
        else if(obj.event === &#39;add&#39;){
           layer.open({
               title:&#39;增加窗口&#39;,
               content:userPage.template,
               yes:function () {
                   var user = page.formToJson($(&#39;#layer_form&#39;).serialize());
                   var data = &#39;user=&#39;+user;
                  $.post(&#39;/doAdd.action&#39;,data,function (res) {
                      userPage.reload(res);
                  });
                  layer.closeAll();
               }
           })

        }
        else if(obj.event === &#39;edit&#39;){
            layer.open({
                title:&#39;编辑窗口&#39;,
                content:userPage.template,
                success:function () {
                    $(&#39;input[name="id"]&#39;).val(userPage.data.id);
                    $(&#39;input[name="username"]&#39;).val(userPage.data.username);
                    $(&#39;input[name="password"]&#39;).val(userPage.data.password);
                    $(&#39;input[name="gender"]&#39;).val(userPage.data.gender);
                    $(&#39;input[name="nichen"]&#39;).val(userPage.data.nichen);
                    $(&#39;input[name="birthday"]&#39;).val(userPage.data.birthday);
                },
                yes: function(){
                    var mgUser = page.formToJson($(&#39;#layer_form&#39;).serialize());
                    var data = &#39;user=&#39;+mgUser;
                    $.post(&#39;/doEdit.action&#39;,data,function (res) {
                        userPage.reload(res);
                    });
                    layer.closeAll();
                }
            })
        }
    });
});

二.服務端部分

Controller層需要接收以下參數,page,limit,要查詢的條件,返回值根據layui文檔給出的默認返回值

 @RequestMapping("/getUserList")
    @ResponseBody
    public PageList<MgUser> getUserList(@RequestParam(required = false,defaultValue = "1") int page,@RequestParam(required = false,defaultValue = "5") int limit,@RequestParam(required = false) String queryStr){
        QueryPo queryPo = null;
        if (!StringUtils.isEmpty(queryStr)){   //性别类型转换
             queryPo = JSONObject.parseObject(queryStr,QueryPo.class);
            if ("1".equals(queryPo.getGender())){
                queryPo.setGender("男");
            }
            if ("2".equals(queryPo.getGender())){
                queryPo.setGender("女");
            }

        }
        PageList pageList = new PageList();
        try {
            if (!StringUtils.isEmpty(queryPo)){ //中文字转码
                if(!StringUtils.isEmpty(queryPo.getKeywords())){
                    queryPo.setKeywords(URLDecoder.decode(queryPo.getKeywords(),"utf-8"));
                }
            }
            List<MgUser> userList = userService.getUserList(page,limit,queryPo);   //根据条件查询分页数据

            pageList.setCode("0");
            pageList.setMsg("ok");
            pageList.setData(userList);
            int count = userService.countUserByExample(queryPo);
            pageList.setCount(count);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            pageList.setCode("-1");
            pageList.setMsg("数据获取异常");
            return pageList;
        }

        return pageList;
    } 

Service層根據條件查詢並分頁

public List<MgUser> getUserList(int page , int limit, QueryPo queryPo) {
        MgUserExample userExample = new MgUserExample();
        MgUserExample.Criteria criteria = userExample.createCriteria();
        if(!StringUtils.isEmpty(queryPo)){
            if (!StringUtils.isEmpty(queryPo.getGender())){
                criteria.andGenderEqualTo(queryPo.getGender());
            }
            if (!StringUtils.isEmpty(queryPo.getKeywords())){
                criteria.andUsernameLike("%"+queryPo.getKeywords()+"%");
            }
        }

        userExample.setStart((page-1)*limit);
        userExample.setLimit(limit);

        List<MgUser> mgUsers = userMapper.selectByExample(userExample);

        return mgUsers;
    } 

注意由於mybatis逆向工程產生的Example沒有limit和page,所以需要自己加上

    private int start;
    private int limit;
    
    public int getStart() {
        return start;
    }

    public void setStart(int start) {
        this.start = start;
    }

    public int getLimit() {
        return limit;
    }

    public void setLimit(int limit) {
        this.limit = limit;
    }

接著修改Mybatis的mapper.xml,需要加上分頁條件

<select id="selectByExample" resultMap="BaseResultMap" parameterType="com.wang.entity.MgUserExample" >
    select
    <if test="distinct" >
      distinct
    </if>
    <include refid="Base_Column_List" />
    from mg_user

    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null" >
      order by ${orderByClause}
    </if>
    <if test="start !=0 or limit!=0">
      limit #{start},#{limit}
    </if>
  </select>

本文轉自:https://www.cnblogs.com/wangxiayun/p/9145638.html

更多layui知識請關注PHP中文網layui教程欄位

以上是layui實作資料表格及分頁的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:cnblogs.com。如有侵權,請聯絡admin@php.cn刪除