Layui 表格table 第一次加载动态设置列

                                                                    Layui 表格table 第一次加载动态设置列

1、PHP传动态数据到前端;前端json一下;循环设置 cols[0] 的值

2、PHP代码

$types = [ 1 => '类型1', 2 => '类型2', 3 => '类型3' ];
foreach ($types as $k => $v){
    $storeName = 'type_'.$k;
    $result[] = [
        'id' => $k,
        'field' => $storeName,
        'title'=> $v
    ];
}
$this->assign('result', $result);
return $this->fetch();

3、JS代码

<script>
    let result = {:json_encode($result)};
    layui.use(['table'], function(){
        let $ = layui.$,
            table = layui.table;

        //动态组装列数据
        let cols = [
                {field: 'name', title: '姓名'},
                {field: 'age', title: '年龄'}
            ];

        //根据result渲染列
        let length = result.length;
        for(let i=0; i<length; i++){
            cols.push({field: result[i]['field'], title: result[i]['title']});
        }
        cols.push({field: 'create_time', title: '创建时间'});

        //表格渲染
        let tableIns = table.render({
            elem: '#id' //表单挂载对象
            ,url: '/././'   //获取数据的后台接口
            ,cols: [cols]
            ,text: {
                none: '暂无相关数据!'
            }
            ,where:{delivery_time: '1579142378'} //默认查找条件,where属性可不设置
            ,page: false    //是否打开分页
            ,parseData: function(res) {
                return {
                    code: res.code,
                    msg: res.msg,
                    count: res.data.count,
                    data: res.data.data
                }
            }
            ,done:function(res, curr, count){
            }
        });
    });
</script>
发布了223 篇原创文章 · 获赞 36 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/qq_36025814/article/details/104020653