1.使用模板方式加载菜单
lay-url=“菜单接口”
lay-headers=“将token带入请求头”,如果没有,去掉就行
在模板中使用console.log 示例: {{# console.log(1) }}
layui.data(‘layuiAdmin’).token 调用本地存储的token,token名需要和本地存储对应
json字段名不需要和这里的一样,json字段名改变,模板里面也要相应的修改
<div class="layui-side layui-side-menu">
<div class="layui-side-scroll">
<script type="text/html" template lay-url="https://easy-mock.com/mock/5c131015dada7b27ac3a5c36/titi/treemenu"
lay-headers="{'x-auth-token': layui.data('layuiAdmin').token}"
lay-done="layui.element.render('nav', 'layadmin-system-side-menu');" id="TPL_layout">
<ul class="layui-nav layui-nav-tree" lay-shrink="all" id="LAY-system-side-menu" lay-filter="layadmin-system-side-menu">
{{#
var path = layui.router().path
,dataName = layui.setter.response.dataName;
layui.each(d[dataName], function(index, item){
var hasChildren = typeof item.list === 'object' && item.list.length > 0
,classSelected = function(){
if(index == 0){
return hasChildren ? 'layui-nav-itemed' : 'layui-this';
}
return '';
}
,url = typeof item.href === 'string' ? item.href : item.name;
}}
<li data-name="{{ item.name || '' }}" data-jump="{{ item.href || '' }}" class="layui-nav-item {{ classSelected() }}">
<a href="javascript:;" {{ hasChildren ? '' : 'lay-href="'+ url +'"' }} lay-tips="{{ item.title }}" lay-direction="2">
<i class="layui-icon {{ item.icon }}"></i>
<cite>{{ item.title }}</cite>
</a>
{{# if(hasChildren){ }}
<dl class="layui-nav-child">
{{# layui.each(item.list, function(index2, item2){
var hasChildren2 = typeof item2.list == 'object' && item2.list.length > 0
,classSelected2 = function(){
if(index==0){
return hasChildren2 ? 'layui-nav-itemed' : 'layui-this';
}
return '';
}
,url2 = typeof item2.href === 'string'
? item2.href
: [item.name, item2.name, ''].join('/');
}}
<dd data-name="{{ item2.name || '' }}" data-jump="{{ item2.href || '' }}"
{{ classSelected2() ? ('class="'+ classSelected2() +'"') : '' }}>
<a href="javascript:;" {{ hasChildren2 ? '' : 'lay-href="'+ url2 +'"' }}>{{ item2.title }}</a>
{{# if(hasChildren2){ }}
<dl class="layui-nav-child">
{{# layui.each(item2.list, function(index3, item3){
var match = path[0] == item.name && path[1] == item2.name && path[2] == item3.name
,url3 = typeof item3.href === 'string'
? item3.href
: [item.name, item2.name, item3.name].join('/')
}}
<dd data-name="{{ item3.name || '' }}" data-jump="{{ item3.href || '' }}"
{{ match ? 'class="layui-this"' : '' }}>
<a href="javascript:;" lay-href="{{ url3 }}">{{ item3.title }}</a>
</dd>
{{# }); }}
</dl>
{{# } }}
</dd>
{{# }); }}
</dl>
{{# } }}
</li>
{{# }); }}
</ul>
</script>
</div>
</div>
2.后台返回的json格式(示例):
{
"code": 200,
"data": [
{
"title": "主页",
"icon": "layui-icon-home",
"list": [
{
"title": "主页",
"icon": "layui-icon-home",
"href": "home/home.html"
}
]
},
{
"title": "系统管理",
"icon": "layui-icon-senior",
"list": [
{
"title": "部门管理",
"href": "systemManage/branch.html"
},
{
"title": "用户管理",
"href": "systemManage/user.html",
"list":[
{
"title": "用户管理1",
"href": "systemManage/user1.html",
}
]
}
]
}
}
3.效果图