layui渲染表格数据

好文章需要耐心阅读…茶凡—Matrix

请添加图片描述

layui 的渲染的数据有方法渲染和自动渲染。

🌿方法渲染:所有数据都写在js代码里面,html 只需要引用它,推荐采用这种方式

🌿自动渲染:所有都写在html 里面包括请求(注意这种写法必须是get请求,而且返回的状态码必须为0,不然会导致数据渲染不上去)需要写的代码重复率高,不推荐。

官方文档:table 数据表格文档 - Layui

1、layui 渲染数据

注意

本文中采用的是 thymeleaf + springboot + java + layui 来创建的项目,如果单纯写html可能会有一些区别。

方法渲染
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org/">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>首页</title>
    <link rel="stylesheet" th:href="@{//unpkg.com/layui@2.6.8/dist/css/layui.css}">
</head>

<body class="layui-layout-body">

<!--头-->
<!--在html的head元素中通过th:replace属性引入,值为模板的路径,
不需要模板的后缀后面::跟的是模板的ID(即公共header页面中th:fragment定义的值)-->
<div th:replace="head :: header"></div>

<div class="layui-body layui-container" style="margin:70px 0px 0px 20px; ">
    <table class="layui-hide" id="test" lay-filter='test'></table>
</div>

<script type="text/javascript" th:inline="none" th:src="@{//unpkg.com/layui@2.6.8/dist/layui.js}"></script>
<script>
    layui.use(['table', 'layer','laypage','form'], function () {
        var $ = layui.jquery,
            layer = layui.layer,
            laypage = layui.laypage,
            form = layui.form,
            table = layui.table;

        table.render({
            elem: '#test',
            id: 'tableId',
            url: 'parent/getParentList',
            method:'get',
            title: '用户信息表',
            totalRow: true,
            height: 520,
            width:550,
            cols: [
                [
                {type: "numbers", fixed: 'aa'}
                ,{type: "checkbox", fixed: 'aa'}
                , {field: 'studentName', title: '学生姓名', width: 100}
                , {field: 'personNo', title: '学号', sort:true ,width: 120}
                , {field: 'departmentId', title: '班级', width: 80 }
                , {field: 'parentDeptId', title: '年级', width: 80}

            ]
            ],
            page: true , // 分页
            elem: '#test',
            limit:10,
            parseData: function (res) {  // 分页效果必须要加这个函数只加 page:true 不起作用。
                var result;
                console.log(this);
                console.log(JSON.stringify(res));
                if (this.page.curr) {
                    result = res.data.slice(this.limit * (this.page.curr - 1), this.limit * this.page.curr);
                } else {
                    result = res.data.slice(0, this.limit);
                }
                return {"code": res.code, "msg": res.msg, "count": res.data.length, "data": result};
            }

        });
    });
    
</script>
</body>
</html>
自动渲染
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org/">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>首页</title>
    <link rel="stylesheet" th:href="@{//unpkg.com/layui@2.6.8/dist/css/layui.css}">
</head>

<body class="layui-layout-body">

<!--头-->
<!--在html的head元素中通过th:replace属性引入,值为模板的路径,
不需要模板的后缀后面::跟的是模板的ID(即公共header页面中th:fragment定义的值)-->
<div th:replace="head :: header"></div>


<div class="layui-body layui-container" style="margin:70px 0px 0px 20px; ">

    <table class="layui-table"
           lay-data="{height:500,width:1260, url:'/parent/getParentList', page:true, id:'test'}"
           lay-filter="test">
        <thead>
        <tr>
            <th lay-data="{checkbox:true}"></th>
            <th lay-data="{field:'departmentId', width:80, sort: true}">班级</th>
            <th lay-data="{field:'parentDeptId', width:80, }">年级</th>
            <th lay-data="{field:'personNo',width:120,}">学号</th>
            <th lay-data="{field:'studentName', width:80  }">学生</th>
        </tr>
        </thead>
    </table>
    
</div>

<script type="text/javascript" th:inline="none" th:src="@{//unpkg.com/layui@2.6.8/dist/layui.js}"></script>
<script>
    layui.use(['table', 'layer','laypage','form'], function () {
        var $ = layui.jquery,
            layer = layui.layer,
            laypage = layui.laypage,
            form = layui.form,
            table = layui.table;
    });

</script>
</body>
</html>
2、后台接口数据格式

后台的就不贴代码了,文章末尾可以获取

请添加图片描述

{
  "msg": "success",
  "code": 0,
  "data": [
    {
      "departmentId": 201505,
      "parentDeptId": 2015,
      "personNo": "201505019",
      "studentName": "何金贝"
    },
    {
      "departmentId": 201508,
      "parentDeptId": 2015,
      "personNo": "201508003",
      "studentName": "卿屹昊"
    },
    {
      "departmentId": 201601,
      "parentDeptId": 2016,
      "personNo": "201601001",
      "studentName": "黄星云"
    }
    ]
  }  

茶凡_Matrix仓亏地址:(CommuteRate: 通勤率后台初版 (gitee.com))

### 使用 LayUI 框架渲染表格的方法或示例 LayUI 是一个前端框架,提供了丰富的组件和功能,其中表格组件是一个非常常用的模块。通过方法渲染的方式,可以将数据从后端传递到前端并动态渲染表格。以下是一个完整的示例及说明: #### 1. 引入 LayUI 确保在项目中正确引入 LayUI 的 CSS 和 JS 文件。可以通过 CDN 或本地文件引入: ```html <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/layui-src/dist/css/layui.css"> <script src="https://cdn.jsdelivr.net/npm/layui-src/dist/layui.js"></script> ``` #### 2. HTML 结构 定义一个容器用于渲染表格,例如: ```html <table id="demo" lay-filter="test"></table> ``` #### 3. JavaScript 方法渲染 使用 `layui.use` 加载表格模块,并调用 `table.render` 方法进行渲染: ```javascript layui.use('table', function() { const table = layui.table; // 渲染表格 table.render({ elem: '#demo', // 绑定的 DOM 元素 height: window.screen.height * 0.59, // 表格高度 url: '/info/list', // 数据接口地址 method: 'post', // 请求方式 contentType: "application/json", // 设置请求头 page: true, // 开启分页 parseData: function(res) { // 解析返回的数据 return { code: 0, // 状态码 msg: "", // 提示信息 count: res.length, // 数据总数 data: res // 数据列表 }; }, cols: [[ // 表头配置 {field: 'infoId', title: 'ID', width: 80, sort: true, fixed: 'left'}, {field: 'countryId', title: '国家名称', width: 80}, {field: 'universityId', title: '用户名', width: 80}, {field: 'directionId', title: '性别', width: 80}, {title: '大学英文', width: 170, templet: '<div>{{d.university.universityNameEN}}</div>'} ]], text: {none: '无数据'} // 当无数据时显示的内容 }); }); ``` #### 4. 后端接口示例 后端需要返回符合 LayUI 表格要求的数据格式。以下是一个 PHP 示例: ```php public function index_data2() { $p = input('p') ?? 1; // 获取当前页码,默认为第一页 $p_n = input('p_n') ?? config('paginate.list_rows'); // 获取每页显示条数,默认为系统配置值 $list = Db::table('tp_goods')->order('goods_id ASC')->limit(($p - 1) * $p_n, $p_n)->select(); // 查询数据 $count = Db::table('tp_goods')->count(); // 查询总记录数 return json(['code' => 0, 'msg' => '加载成功!', 'data' => $list, 'count' => $count]); // 返回数据 } ``` #### 5. 常见问题及解决方法 - **问题:表格无法渲染数据** 可能原因:后端返回的数据格式不符合 LayUI 的要求。确保返回的数据包含 `code`、`msg`、`count` 和 `data` 字段[^1]。 - **问题:请求方式不匹配** 默认情况下,LayUI 使用 GET 请求获取数据。如果后端只支持 POST 请求,则需要在 `table.render` 中添加 `method: 'post'` 属性[^2]。 - **问题:分页功能无效** 确保后端返回的数据中包含 `count` 字段,表示总记录数。同时,前端需要开启分页功能 `page: true`[^4]。 #### 6. 扩展功能 可以通过 `templet` 自定义列内容,或者通过工具栏按钮实现行操作。例如: ```html <script type="text/html" id="barDemo"> <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> ``` 在 `table.render` 中添加工具栏配置: ```javascript toolbar: '#toolbarDemo', // 工具栏模板 defaultToolbar: ['filter', 'exports', 'print', { // 自定义工具栏按钮 title: '提示', layEvent: 'LAYTABLE_TIPS', icon: 'layui-icon-tips' }], ``` --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值