laytree目前的功能有限,但是樣式還是挺好看的,能完成基本的樹形展示以及點擊的回調操作。
在 application\\index\\controller\\Layer.php 中新建
~~~
// laytree
public function layTree()
{
if(request()->isAjax()){
$data = [
[ 'id' => 1, 'name' => '江蘇省', 'pid' => 0],
[ 'id' => 2, 'name' => '徐州市', 'pid' => 1],
[ 'id' => 3, 'name' => '睢寧縣', 'pid' => 2],
[ 'id' => 4, 'name' => '雙溝鎮', 'pid' => 3],
[ 'id' => 5, 'name' => '王集鎮', 'pid' => 3],
[ 'id' => 6, 'name' => '銅山區', 'pid' => 2],
[ 'id' => 7, 'name' => '張集鎮', 'pid' => 6],
[ 'id' => 8, 'name' => '大黃山鎮', 'pid' => 6],
[ 'id' => 9, 'name' => '南京市', 'pid' => 1],
[ 'id' => 10, 'name' => '江寧區', 'pid' => 9],
[ 'id' => 11, 'name' => '鼓樓區', 'pid' => 9],
[ 'id' => 12, 'name' => '浙江省', 'pid' => 0],
[ 'id' => 13, 'name' => '杭州市', 'pid' => 12],
[ 'id' => 14, 'name' => '西湖區', 'pid' => 13]
];
$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(['code' => 1, 'data' => $tree, 'msg' => 'ok']);
}
return $this->fetch();
}
~~~
他需要的數據格式,你可以到官網去查看。這里我整理出的是我總結到的最快的構建出子孫數的方法,無需遞歸。
新建 application\\index\\view\\layer\\laytree.html
~~~
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>樹模塊 - layui</title>
<link href="/static/layui/css/layui.css" rel="stylesheet">
<style>
body{padding: 50px 100px;}
</style>
</head>
<body>
<ul id="demo"></ul>
<script src="/static/js/jquery.min.js?v=2.1.4"></script>
<script src="/static/layui/layui.js"></script>
<script>
$(function(){
layui.use('tree', function(){
$.getJSON("{:url('layer/laytree')}", function(res){
var tree = layui.tree({
elem: '#demo' //指定元素
//,check: 'checkbox' //勾選風格
,skin: 'as' //設定皮膚
//,target: '_blank' //是否新選項卡打開(比如節點返回href才有效)
,drag: true
,click: function(item){ //點擊節點回調
console.log(item)
}
,nodes: res.data
});
});
});
});
</script>
</body>
</html>
~~~
訪問[http://www.phper.com/index/layer/laytree](http://www.phper.com/index/layer/laytree)就會看到如下的樹形菜單
