当前位置: 首页 > Web前端 > JavaScript

实现读取路由json文件渲染菜单

时间:2023-03-27 17:22:38 JavaScript

在原生前端项目中,使用json文件配置路由方式,修改菜单跳转的链接更方便,下面我们来实现一下:以layui-nav导航组件为例,结构为分为一级和二级菜单,顶部导航为一级,左栏菜单为二级菜单,使用iframe作为路由视图,页面结构:

一个
创建菜单路由当前目录下的表menu.json,内容如下:[{"caption":"Menu1","href":"../org/org.html","default":"layui-this"},{"caption":"用户马nagement","href":"../user/user.html"},{"caption":"xx管理"},{"caption":"权限管理","children":[{"caption":"位置设置","href":"../system/position/position.html"},{"caption":"模块管理","href":"../system/log/log.html?type=16"}]},{"caption":"系统配置","align":"right","children":[{"caption":"操作日志","href":"../system/log/log.html?type=4"},{"caption":"登录日志","href":"../system/log/log.html?type=8"}]}]caption是菜单对应的文字,href是菜单对应的地址需要跳转到,childrenSubmenu,default默认选中,对齐方式menuRender.js"usestrict";/***menuRender.js读取菜单json并渲染**/functionhideSideMenuLeft(){$(".layui-side").hide();$(".layui-body").css("left","0px");};hideSideMenuLeft();functionshowSideMenuLeft(){$(".layui-body").css("left","20rem");$(".layui-side").show();}functionrenderLeftMenu(meunItemArr){varmeunLeftItemArr=[];meunItemArr.forEach(function(left_item,idx_l){var$menuItem=$('');$menuItem.click(function(){$(this).parent().find('.layui-this').removeClass('layui-this');$(this).addClass('layui-this');$("#appContent").attr("src",$(this).find('a').attr("data-url"));})meunLeftItemArr.push($menuItem);});$("#menu-list-left").empty().append(meunLeftItemArr);}$.getJSON("menu.json",function(data){//获取json内容并遍历开始染一级菜单varmeunTopItemArr=[];data.forEach(function(top_item,idx){var$menuItem=$(''+(top_item.caption||"")+'');if(top_item.children&&top_item.children.length){$menuItem.data("children",top_item.children);if(top_item.default==="layui-this"){//如果当前默认菜单有二级菜单需要渲染renderLeftMenu(top_item.children);showSideMenuLeft();}}else{$menuItem.data("children",[]);}//一级菜单绑定事件和渲染$menuItem.click(function(){varthisChild=$(this).data("children");if(thisChild.length){renderLeftMenu(thisChild);showSideMenuLeft();}else{hideSideMenuLeft();}$("#appContent").attr("src",$(this).find('a').attr("data-url"));});meunTopItemArr.push($menuItem);});$("#menu-list").append(meunTopItemArr);});$("#appContent").attr("src","../org/org.html");

最新推荐
猜你喜欢