一、简单
var treedata=[];tree.render({elem: '#addLeftType',id: 'demoId',data: treedata,showCheckbox: true,oncheck: function(obj){console.log(obj.data); // 得到当前点击的节点数据console.log(obj.checked); // 节点是否被选中console.log(obj.elem); // 得到当前节点元素},edit: ['add', 'update', 'del'] // 开启节点的右侧操作图标});get_tree_data(0);//初始化// 使用 layui 的 ajax 方法来获取树节点数据function get_tree_data(id){$.ajax({type:'post',url: "{:url('classif_listjson')}",data: {id:id},success:function(response){tree.reload('demoId', {data:response,});tree.setChecked('demoId', [1,2]); //单个勾选 id 为 1 的节点}});};
初始化 默认选中:只能这个位置才能生效
tree.setChecked('demoId', [1,2]); //单个勾选 id 为 1 的节点
二、复杂(只能单选,二级):增加、编辑、删除功能
//tree组件 操作 开始var show_btn = [];var show_btn_ids='';var array_ids=[];function get_tree_id(checkarr){ for(var i=0;i<checkarr.length;i++){ if(checkarr[i].children){get_tree_id(checkarr[i].children)}else{show_btn_ids += checkarr[i].id+',';array_ids.push(checkarr[i].id);$("#classify_ids").val(show_btn_ids);}} }var treedata=[];//用来修改后的节点数据var update_treedata=[];//渲染var inst1 = tree.render({elem: '#addLeftType' //绑定元素,id: 'demoId',edit: ['add', 'update', 'del'],showCheckbox: true,data:treedata,click: function(obj){//layer.msg(JSON.stringify(obj.data));},oncheck: function(obj){// console.log(obj); //得到当前点击的节点数据 show_btn_ids = '';$("#classify_ids").val('');$("#showLeftType").html('');//获得选中的节点var checkData = tree.getChecked('demoId');$("#showLeftType").html("");//console.log(checkData.length)// 取消其它选中,只能单选uncheckAllExceptOne()get_tree_id(checkData); },operate: function(obj){var type = obj.type; //得到操作类型:add、edit、delvar data = obj.data; //得到当前节点的数据var elem = obj.elem; //得到当前节点元素//Ajax 操作var id = data.id; //得到节点索引var all_id = data.pid_all.split(","); if(type === 'add'){ //增加节点addType(id,all_id);//返回 key 值return '增加';} else if(type === 'update'){ //修改节点var title = elem.find('.layui-tree-txt').html()$.ajax({type: "post",url: "{:url('classif_add')}",dataType:"json", //返回格式为jsondata: {id:id,title:title,field:'name',action:'ajax_update'},success: function(data){layer.msg(data.msg);$("#"+id).text(title);},error: function(){layer.msg('更新失败!');}});} else if(type === 'del'){ //删除节点$.ajax({type: "post",url: "{:url('classif_add')}",dataType:"json", //返回格式为jsondata: {id:id,del_is:1,action:'ajax_del'},success: function(data){layer.msg(data.msg);if(data.code==200){//获得选中的节点var checkData = tree.getChecked('demoId');//清空选中array_ids=[];//重新获取选中idget_tree_id(checkData); //treedata 结构数据,id递归删除对应id,array_ids给默认选中的id加上update_treedata= delete_tree_id(treedata,id,array_ids,"del",0,all_id);//重新渲染组件tree.reload('demoId', {data:update_treedata});//清空$("#showLeftType").html("");//再次获得选中的节点var checkData = tree.getChecked('demoId');//再次清空选中array_ids=[];//再次重新获取选中idget_tree_id(checkData); }},error: function(){layer.msg('更新失败!');}});};}});//取消除了当前选中所有选项function uncheckAllExceptOne(checkboxId) {var checkboxes = document.querySelectorAll('#addLeftType input[type="checkbox"]');for (var i = 0; i < checkboxes.length; i++) {checkboxes[i].checked = false;}}function get_page_data(id){$.ajax({type:'post',url: '{:url('classif_listjson')}',data: {id:id},success:function(response){treedata = response.data;if(response.code!=200){treedata =[{title:response.msg,id:99999999,children:[]}];}tree.reload('demoId', {data:treedata});{notempty name="$rs"}tree.setChecked('demoId', [{$rs['classify1']},{$rs['classify2']}]); //单个勾选 id 为 1 的节点{/notempty}}});};var p_id=0;var add_terr_item_title="未命名";get_page_data({$id});tree.setChecked('demoId', [1, 2]); // 批量勾选 id 为 1,3 的节点//操作节点type:del删除 add 添加function delete_tree_id(data,id,array_ids,type,addid,all_id){ var is_data=data;var one_data=[];var p_spread=true;for(var i=0;i<data.length;i++){if(id==data[i].id&&type=="del"){is_data.splice(i,1);}else if(type=="add"&&(id==data[i].id)){if(is_data[i].children){is_data[i].children.push({id:addid,title:add_terr_item_title,pid_all:all_id.toString()+','+addid});}else{is_data[i].children=[];is_data[i].children.push({id:addid,title:add_terr_item_title,pid_all:all_id.toString()+','+addid});}}for (let index = 0; index < array_ids.length; index++) {var acid = array_ids[index];if(data[i]&&acid==data[i].id){if(is_data[i]){is_data[i].checked=true;}}} //父节点展开if(data[i]&&data[i].id==id){is_data[i].spread=p_spread;//父节点展开}if(all_id){for (let k = 0; k <all_id.length; k++) {const sp_id = all_id[k];if(data[i]&&sp_id==data[i].id){is_data[i].spread=p_spread;//父节点展开}}}if(data[i]&&data[i].children){delete_tree_id(data[i].children,id,array_ids,type,addid,all_id);}}one_data=is_data;return one_data;}function addType(pid,all_id){var typetitle = $("#typetitle").val();var titleif(pid==p_id||pid==""||pid==0||pid==null||pid==undefined){title = typetitle? typetitle:add_terr_item_title;}else{title=add_terr_item_title;}add_terr_item_title=title;$.ajax({type: "post",url: "{:url('classif_add')}",dataType:"json", //返回格式为jsondata: {pid:pid,title:title,level_limit:{$level_limit}},success: function(data){layer.msg(data.msg);if(data.code==200){//获得选中的节点var checkData = tree.getChecked('demoId');//清空选中array_ids=[];//重新获取选中idget_tree_id(checkData); //treedata 结构数据,id递归删除对应id,array_ids给默认选中的id加上,all_idupdate_treedata= delete_tree_id(treedata,pid,array_ids,"add",data.add_id,all_id);if((pid==0||pid==null||pid==undefined||pid==""||pid==p_id)){update_treedata.push({id:data.add_id,title:add_terr_item_title,pid_all:p_id.toString()+','+data.add_id});}//重新渲染组件tree.reload('demoId', {data:update_treedata});//清空$("#showLeftType").html("");//再次获得选中的节点var checkData = tree.getChecked('demoId');//再次清空选中array_ids=[];//再次重新获取选中idget_tree_id(checkData); add_terr_item_title="未命名";}else{//重新渲染组件tree.reload('demoId');}},error: function(){layer.msg('更新失败!');}});}$("#addType").click(function(){//更新后台数据addType(p_id,0);})//tree组件 操作 结束
去掉uncheckAllExceptOne()就可以多选了
表单提交的一些判断
/* 监听提交 */form.on('submit(component-form-demo1)', function(data){/* 启动加载... */var indexload = layer.load(1, {shade: [0.1,'#fff'] //0.1透明度的白色背景});// 加入分类var data = JSON.parse(JSON.stringify(data.field));var checkData = tree.getChecked('demoId');if (Object.keys(checkData).length === 0) {layer.close(indexload);/* 关闭加载弹层... */layer.msg('请选择分类');return}var classify1 = checkData[0]['id'];var classify2 = checkData[0]?.children?.[0]?.id;;data.classify1=classify1;data.classify2=classify2;var addData = JSON.stringify(data);$.ajax({url: "{:url('add')}",type: "post",dataType:"json", //返回格式为jsondata: {data:addData},success: function(data) {layer.close(indexload);/* 关闭加载弹层... */layer.msg(data['msg']);/* 延迟2秒刷新... */if(data['code']==200){setTimeout(function(){window.location.reload() },2000)}},error: function() {layer.close(indexload);/* 关闭加载弹层... */layer.msg('{$form_server_error_title}');}});});