search
HomeWeb Front-endLayui TutorialSeveral tips for using layui data tables

Several tips for using layui data tables

Nov 23, 2019 pm 02:38 PM
layui

Using table components can improve a lot of development efficiency. Currently, the mainstream data table components include bootstrap table, layui table, easyUI table, etc. This tutorial recommends using the layui framework to set up data tables.

Several tips for using layui data tables

Recommended: layui framework quick start
1. Three initial rendering methods

I Let’s start with the simplest initialization form. If I post all the code directly, you may feel dizzy

Several tips for using layui data tables

1, method rendering:

<table class="layui-table" id="layui_table_id" lay-filter="dataTable"></table>
var table = layui.table
            ,form = layui.form;
    layui.use(&#39;table&#39;, function () {  // 引入 table模块
        table.render({
            id:"dataTable",//
            elem: &#39;#layui_table_id&#39;,//指定表格元素
            url: &#39;/menu/menuList.ajax&#39;,  //请求路径
            cellMinWidth: 20 //全局定义常规单元格的最小宽度,layui 2.2.1 新增
            ,skin: &#39;line &#39; //表格风格 line (行边框风格)row (列边框风格)nob (无边框风格)
           //,even: true    //隔行换色
            ,page: true  //开启分页
            ,limits: [10,20,50]  //每页条数的选择项,默认:[10,20,30,40,50,60,70,80,90]。
            ,limit: 10 //每页默认显示的数量
            ,method:&#39;post&#39;  //提交方式
           ,cols: [[
                {type:&#39;checkbox&#39;}, //开启多选框
                {
                    field: &#39;menuId&#39;, //json对应的key
                    title: &#39;ID&#39;,   //列名
                    sort: true   // 默认为 false,true为开启排序
                }
            ]]
        });
    });

JSON data format returned by java background

{
code: 0, 
count: 8,  //总行数
data: [,…], //表格数据
msg: ""
}

2. Automatic rendering method (the following code is provided by the official, the automatic rendering method is suitable for complex line headers, it is generally recommended to use the above method for rendering)

<table class="layui-table" lay-data="{height:315, url:&#39;/demo/table/user/&#39;, page:true, id:&#39;test&#39;}" lay-filter="test">
  <thead>
    <tr>
      <th lay-data="{field:&#39;id&#39;, width:80, sort: true}">ID</th>
      <th lay-data="{field:&#39;username&#39;, width:80}">用户名</th>
      <th lay-data="{field:&#39;sex&#39;, width:80, sort: true}">性别</th>
      <th lay-data="{field:&#39;city&#39;}">城市</th>
      <th lay-data="{field:&#39;sign&#39;}">签名</th>
      <th lay-data="{field:&#39;experience&#39;, sort: true}">积分</th>
      <th lay-data="{field:&#39;score&#39;, sort: true}">评分</th>
      <th lay-data="{field:&#39;classify&#39;}">职业</th>
      <th lay-data="{field:&#39;wealth&#39;, sort: true}">财富</th>
    </tr>
  </thead>
</table>

Second, how to add an edit button

var table = layui.table
            ,form = layui.form;
    layui.use(&#39;table&#39;, function () {  // 引入 table模块
        table.render({
            id:"dataTable",//
            elem: &#39;#layui_table_id&#39;,//指定表格元素
            url: &#39;/menu/menuList.ajax&#39;,  //请求路径
            cellMinWidth: 20 //全局定义常规单元格的最小宽度,layui 2.2.1 新增
            ,skin: &#39;line &#39; //表格风格 line (行边框风格)row (列边框风格)nob (无边框风格)
           //,even: true    //隔行换色
            ,page: true  //开启分页
            ,limits: [10,20,50]  //每页条数的选择项,默认:[10,20,30,40,50,60,70,80,90]。
            ,limit: 10 //每页默认显示的数量
            ,method:&#39;post&#39;  //提交方式
,done: function(res, curr, count) { //表格数据加载完后的事件
    //调用示例
    layer.photos({//点击图片弹出
        photos: &#39;.layer-photos-demo&#39;
        ,anim: 1 //0-6的选择,指定弹出图片动画类型,默认随机(请注意,3.0之前的版本用shift参数)
    });
    //如果是异步请求数据方式,res即为你接口返回的信息。
    //如果是直接赋值的方式,res即为:{data: [], count: 99} data为当前页数据、count为数据总长度
    console.log(res);

    //得到当前页码
    console.log(curr);

    //得到数据总量
    console.log(count);
}
    ,cols: [[ {type:&#39;checkbox&#39;}, //开启多选框  { field: &#39;menuId&#39;, //json对应的key title: &#39;ID&#39;, //列名 sort: true // 默认为 false,true为开启排序  },{ fixed: &#39;right&#39;, title: &#39;操作&#39;, width: 215, align:&#39;center&#39;, toolbar: &#39;#barDemo&#39; //绑定按钮组 } ]] }); });
//监听工具条
table.on(&#39;tool(dataTable)&#39;, function(obj){ //注:tool是工具条事件名,test是table原始容器的属性 lay-filter="对应的值"
    var data = obj.data //获得当前行数据
            ,layEvent = obj.event; //获得 lay-event 对应的值
    if(layEvent === &#39;detail&#39;){
     layui.alert(JSON.stringifr(data)) ; //将编辑的行信息转为json字符串
        layer.msg(data.attrId);
    } else if(layEvent === &#39;del&#39;){
        layer.msg(&#39;删除&#39;+data.menuId);
        console.log(table)
    } else if(layEvent === &#39;edit&#39;){
       
    });
    }
});
<script type="text/html" id="barDemo">  // id和toolbar 属性绑定
     <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>
</script>

Three, how to add form components to the table (I will recommend 2 types below )

1, using the module engine method (this method is more troublesome, I personally recommend the second one)

<!--  是否显示 -->
<script type="text/html" id="isShow">  // 请注意 id之间的关联
    {{#  if(d.menuDisplay === &#39;Y&#39;){ }}
    <input type="checkbox" name="menuDisplay" value="{{d.menuId}}" lay-skin="switch" lay-text="显示|隐藏" lay-filter="isShow" checked>
    {{#  } else { }}
    <input type="checkbox" name="menuDisplay" value="{{d.menuId}}" lay-skin="switch" lay-text="显示|隐藏" lay-filter="isShow" >
    {{#  } }}
</script>
{   //在表格对象cols属性中添加
    field: &#39;menuDisplay&#39;,  /
    title: &#39;是否显示&#39;,
    templet: &#39;#isShow&#39;, //模板关联以上定义的
    unresize: true,
    filter: "isShow",
    sort: false
}

2, using the function method

{
    field: &#39;menuDisplay&#39;,
    title: &#39;是否显示&#39;,

    unresize: true,
    filter: "isShow",
    sort: false,
    templet: function (d) {
        if (d.menuDisplay == ‘Y’) {
            return` <input type = "checkbox"
            name = "menuDisplay"
            value = "`+d.menuId+`"
            lay - skin = "switch"
            lay - text = "显示|隐藏"
            lay - filter = "isShow" > `;
        } else {
            return` <input type = "checkbox"
            name = "menuDisplay"
            value = "`+d.menuId+`"
            lay - skin = "switch"
            lay - text = "显示|隐藏"
            lay - filter = "isShow"
            checked > `;
        }
    }
}

4. Display pictures

{
                    field: &#39;img&#39;,
                    title: &#39;图片&#39;,
                    unresize: true,
                    sort: false,
                    //style:&#39;height:100px;&#39;,
                    templet:function (d) {
                        return `<div class="layer-photos-demo" onclick="img_click()" style="cursor:pointer;">
                                      <img src="/static/imghwm/default1.png"  data-src="/images/bug-success-bg.jpg"  class="lazy"  layer-pid="图片id,可以不写"  layer-  alt="图片名">
                                    </div>`;
                    }
                }

Several tips for using layui data tables Bind attributes after the table data is loaded

Full code: https: //gitee.com/gezi441/layui-table

The above is the detailed content of Several tips for using layui data tables. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
How do I use Layui's flow module for infinite scrolling?How do I use Layui's flow module for infinite scrolling?Mar 18, 2025 pm 01:01 PM

The article discusses using Layui's flow module for infinite scrolling, covering setup, best practices, performance optimization, and customization for enhanced user experience.

How do I use Layui's element module to create tabs, accordions, and progress bars?How do I use Layui's element module to create tabs, accordions, and progress bars?Mar 18, 2025 pm 01:00 PM

The article details how to use Layui's element module to create and customize UI elements like tabs, accordions, and progress bars, highlighting HTML structures, initialization, and common pitfalls to avoid.Character count: 159

How do I customize the appearance and behavior of Layui's carousel module?How do I customize the appearance and behavior of Layui's carousel module?Mar 18, 2025 pm 12:59 PM

The article discusses customizing Layui's carousel module, focusing on CSS and JavaScript modifications for appearance and behavior, including transition effects, autoplay settings, and adding custom navigation controls.

How do I use Layui's carousel module to create image sliders?How do I use Layui's carousel module to create image sliders?Mar 18, 2025 pm 12:58 PM

The article guides on using Layui's carousel module for image sliders, detailing steps for setup, customization options, implementing autoplay and navigation, and performance optimization strategies.

How do I configure Layui's upload module to restrict file types and sizes?How do I configure Layui's upload module to restrict file types and sizes?Mar 18, 2025 pm 12:57 PM

The article discusses configuring Layui's upload module to restrict file types and sizes using accept, exts, and size properties, and customizing error messages for violations.

How do I use Layui's layer module to create modal windows and dialog boxes?How do I use Layui's layer module to create modal windows and dialog boxes?Mar 18, 2025 pm 12:46 PM

The article explains how to use Layui's layer module to create modal windows and dialog boxes, detailing setup, types, customization, and common pitfalls to avoid.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function