Layui树形组件的使用

Layui的Tree组件使用

生成layui所需要的json格式

其中修改了tree.js源码的title字段

原因是我数据库字段为name 而layui源码只读取了title

public function layui()
{

    $list1 = db('goods_cate')->select()$list = db('picture')->select()$data = array_merge($list,$list1)$res = [];
    $tree = [];

    //整理数组
    foreach( $data as $key=>$vo ){
        $res[$vo['id']] = $vo;
        $res[$vo['id']]['children'] = [];
    }
    unset( $data );

    //查询子孙
    foreach( $res as $key=>$vo ){
        if( $vo['pid'] != 0 ){
            $res[$vo['pid']]['children'][] = &$res[$key];
        }
    }

    //去除杂质
    foreach( $res as $key=>$vo ){
        if( $vo['pid'] == 0 ){
            $tree[] = $vo;
        }
    }
    unset($res);

        return  json($tree);

}

前端获取并读取

<blockquote class="layui-elem-quote">Layui-Tree</blockquote>
<div id="test9" class="demo-tree demo-tree-box"></div>
<script>
layui.use(['tree', 'util'], function(){
      var tree = layui.tree
      ,layer = layui.layer
      ,util = layui.util

      $.ajax({
        'url':'/index/index/layui',
        'type':'post',
        success:function(suc){

             tree.render({
                elem: '#test9'
                ,data: suc
                    // ,showLine: false  //是否开启连接线
                ,edit: ['add', 'update', 'del'] //操作节点的图标
                ,click: function(obj){
                  layer.msg(JSON.stringify(obj.data.name));
                }
                ,operate: function(obj){
                    var type = obj.type; //得到操作类型:add、edit、del
                    var data = obj.data; //得到当前节点的数据
                    var elem = obj.elem; //得到当前节点元素

                    //Ajax 操作
                    var id = data.id; //得到节点索引
                    if(type === 'add'){ //增加节点
                      //返回 key 值
                      console.log('add')
                    } else if(type === 'update'){ //修改节点
                      console.log(elem.find('.layui-tree-txt').html()); //得到修改后的内容
                    } else if(type === 'del'){ //删除节点
                      console.log('del');
                    };
                }
            });
        }
    })

});
</script>

为您推荐