主要有基礎參數和 數據源屬性
layui 官方文檔:https://www.layui.com/doc/modules/tree.html
后台獲取數據源 JSON 方法
調用獲取tree需要的數據源:
//查詢所有的最頂級菜單 List<Menu> childrenMenus = menuServiceImpl.list(new QueryWrapper<Menu>().isNull("parent_id")); List<JSONObject> jsonObjects = menuServiceImpl.menuData(childrenMenus);
public List<JSONObject> menuData(List<Menu> rootMenus) { JSONObject jsonObject = new JSONObject(); List<JSONObject> l1 = new ArrayList<>(); for (Menu menu : rootMenus) { jsonObject = new JSONObject(); Integer menuId = menu.getId(); jsonObject.put("id", menuId); jsonObject.put("spread",true);//是否展開。 //jsonObject.put("checked",true);//是否初始為選中狀態,默認false jsonObject.put("title", menu.getName()); List<Menu> childrenMenus = list(new QueryWrapper<Menu>().eq("parent_id", menuId)); //jsonObject.put("href", menu.getAttributes().get("href"));//rr.getAttributes() if (!CollectionUtils.isEmpty(childrenMenus)) { List<JSONObject> lss = menuData(childrenMenus); jsonObject.put("children", lss); } l1.add(jsonObject); } return l1; }
前段layui,js
/***************************** 分配權限 ***********************************/ layui.use('tree', function(){ var tree = layui.tree; const datas = [[${treeData}]]; //渲染 var inst1 = tree.render({ id:'menuTreeId' ,elem: '#tree' //綁定元素 ,data:datas //,edit:['add','update', 'del'] ,spread: true //是否初始展開,默認false ,accordion: false //是否開啟手風琴模式,默認 false ,showLine:true //是否開啟連接線,默認為true,為false 文件夾左邊出現三角符號 ,text: { defaultNodeName: '未命名' //節點默認名稱 ,none: '無數據' //數據為空時的提示文本 } ,checked: true //是否初始為選中狀態,默認false ,showCheckbox: true //是否顯示復選框 ,click: function(obj){ console.log(obj.data); //得到當前點擊的節點數據 console.log(obj.state); //得到當前節點的展開狀態:open、close、normal console.log(obj.elem); //得到當前節點元素 console.log(obj.data.children); //當前節點下是否有子節點 } ,oncheck: function(obj){//復選框點擊的回調 console.log(obj.data); //得到當前點擊的節點數據 console.log(obj.checked); //得到當前節點的展開狀態:open、close、normal console.log(obj.elem); //得到當前節點元素 } }); }); function showTright(){ layui.use('layer', function(){ layer = layui.layer; }); layer.open({ type: 1, area: ['500px', '800px'], content: $('#dialog-tright') //這里content是一個DOM,注意:最好該元素要存放在body最外層,否則可能被其它的相對元素所影響 }); } function save() { var tree = layui.tree; //獲得選中的節點 var checkData = tree.getChecked('menuTreeId'); console.log("進入save()方法"+JSON.stringify(eachJsonTree(checkData)));//測試已轉換為一維數組 } //深度遍歷,多維數組轉變為一維數組 function eachJsonTree(data) { var result = []; // 存放結果 (function traverse(node) { node.forEach(i => { result.push({ id: i.id, title: i.title, }); // 有子數據的先遍歷子數據 i.children && traverse(i.children) }) })(data); return result; } //廣度遍歷,多維數組轉換為一維數組 function gothrough(data) { const queue = [...data]; const result = []; while (true) { const next = queue.shift(); if (!next) { break; } result.push({ id: next.id, title: next.title }); if (Array.isArray(next.children)) { queue.push(...next.children); } } return result; }
參考鏈接:http://www.imooc.com/wenda/detail/511049