el-menu动态加载路由,菜单的解决方案

发布时间:2023-11-26 10:30

先看需要实现的效果

\"在这里插入图片描述\"
这里有一级也有二级菜单,注意二级菜单的父目录(”选项设置“点击不会跳转,只是展开目录),然后点击去详情页,需要跳到一个隐藏的路由,不在菜单展示的路由\"在这里插入图片描述\"
还有一点要注意,就是这里有两个router-view,整个页面是一个router-view,可以由LoginView和HomeView替换(当前看到的页面),而HomeView下又有一个router-view,需要用来展示部门,系统,超时,员工设置,不合格品列表和不合格品详情页。


以上的信息均需要在数据库的表中体现
先看看直接写在代码里需要哪些操作

const routes = [
  {
    path: '',
    name: 'login',
    component: LoginView,
  }
  ,
  {
    component: HomeView,
    children: [
      {
        path: '/home',
        name: '不合格品列表',
        component: BelowStandard
      },
      {
        path: '/product/:id',
        name: '不合格品详情',
        component: BelowStandardDetail
      }
    ]
  },
  {
    component: HomeView,
    name: '选项设置',
    children: [
      {
        path: '/employee',
        name: '员工设置',
        component: EmployeeConfig,
      },
      {
        path: '/department',
        name: '部门设置',
        component: DepartmentConfig
      },
      {
        path: '/system',
        name: '系统设置',
        component: SystemConfig
      },
      {
        path: '/warn',
        name: '超时提醒',
        component: WarmConfig
      }
    ]
  },
  {
    component: HomeView,
    children: [
      {
        path: '/statistics',
        name: '统计',
        component: DailyStatistics
      }
    ]
  },
  {
    component: HomeView,
    children: [
      {
        path: '/log',
        name: '日志管理',
        component: LogManager
      }
    ]
  },
]

这是路由,当要动态从数据库加载时,就不能写在这

<el-menu
            router
            active-text-color="#ffd04b"
            background-color="#000"
            class="el-menu-vertical-demo"
            :default-active="this.$route.path"
            text-color="#fff"
            @open=""
            @close=""
        >
          <el-menu-item index="/home">
            <template #title>
              不合格品列表
            </template>
          </el-menu-item>
          <el-sub-menu index="/subMenuConfig">
            <template #title>
              选项设置
            </template>
            <el-menu-item index="/department">部门设置</el-menu-item>
            <el-menu-item index="/system">系统设置</el-menu-item>
            <el-menu-item index="/warn">超时设置</el-menu-item>
            <el-menu-item index="/employee">员工设置</el-menu-item>
          </el-sub-menu>
          <el-menu-item index="/statistics">
            <span>统计</span>
          </el-menu-item>
          <el-menu-item index="/log">
            <span>日志管理</span>
          </el-menu-item>
        </el-menu>

这是el-menu开启了路由功能,所以能跳转路由,当动态加载的时候,这部分需要改造成v-for

数据库

\"在这里插入图片描述\"

说明:parent_id为0的即是一级目录,但是一级目录里一部分可以直接展示界面,一部分是展开二级目录,我这是以component字段为home/HomeView.vue来区分是展示二级目录。


现在开始写后端程序,返回菜单的json格式数据。
\"在这里插入图片描述\"

List<Menu> menuList = menuMapper.getMenuByUserId(UserUtils.getLoginUser().getId());
//根据ParentId分组
Map<Integer, List<Menu>> map = menuList.stream().collect(Collectors.groupingBy(Menu::getParentId, TreeMap::new,Collectors.toList()));
List<Menu> menus = map.get(0);//一级菜单
menus.forEach(menu->{//给有二级菜单的目录设置children属性
    List<Menu> children = map.get(menu.getId());
    menu.setChildren(children);
});
return menus;

从数据库查询到的数据格式如图,然后分一级二级菜单处理后,再返回前端

[
{
"name": "不合格品列表",
"path": "/home",
"component": "product/BelowStandard.vue",
"orderNum": 1,
"parentId": 0,
"isHidden": false,
"children": null
},
{
"name": "选项设置",
"path": "/subMenuConfig",
"component": "home/HomeView.vue",
"orderNum": 2,
"parentId": 0,
"isHidden": false,
"children": [
				{
				"name": "员工设置",
				"path": "/employee",
				"component": "config/EmployeeConfig.vue",
				"orderNum": 1,
				"parentId": 2,
				"isHidden": false,
				"children": null
				},
				{
				"name": "部门设置",
				"path": "/department",
				"component": "config/DepartmentConfig.vue",
				"orderNum": 2,
				"parentId": 2,
				"isHidden": false,
				"children": null
				},
				{
				"name": "系统设置",
				"path": "/system",
				"component": "config/SystemConfig.vue",
				"orderNum": 3,
				"parentId": 2,
				"isHidden": false,
				"children": null
				},
				{
				"name": "超时提醒",
				"path": "/warn",
				"component": "config/WarmConfig.vue",
				"orderNum": 4,
				"parentId": 2,
				"isHidden": false,
				"children": null
				}
]
},
{
"name": "统计",
"path": "/statistics",
"component": "statistics/DailyStatistics.vue",
"orderNum": 3,
"parentId": 0,
"isHidden": false,
"children": null
},
{
"name": "日志管理",
"path": "/log",
"component": "log/LogManager.vue",
"orderNum": 4,
"parentId": 0,
"isHidden": false,
"children": null
},
{
"name": "不合格品详情",
"path": "/product/:id",
"component": "product/BelowStandardDetail.vue",
"orderNum": 5,
"parentId": 0,
"isHidden": true,
"children": null
}
]

前端得到数据之后进行处理,再添加到路由,过程中遇到一个问题,vue-router4版本去掉addRoutes换成addRoute带来的问题困扰我很久,详情可以查看另一篇笔记:
第一次push路由不匹配

初始化路由:

router.beforeEach((to, from, next) => {//配置路由守卫
    if(to.path==='/'){
        next()
    }else if(store.state.user.id){
        initMenus(router,store,next,to)
    }else{
        next({ path: '/',query: {redirect: to.path}});
    }
});

export const initMenus = (router, store,next,to) => {//按F5刷新的话vuex里的会被清空,长度变为0
    if (store.state.menu !== null) {
        next()
    }else {
        axios.get("/menu").then(response => {
            if (response) {
                let responseData = response.data
                if (responseData.flag) {
                    store.state.menu = responseData.data
                    initRoute(router,store.state)
                    next({...to,replace:true})//解决router4版本的第一次路由不匹配问题
                } else {
                    this.$ElMessage.error('请求菜单失败')
                }
            }
        })
    }
}

const initRoute = (router,state)=> {
    const loadView = view => {//这种引入方式控制台不会报警告
        // 路由懒加载
        return () => import(`@/views/${view}`)
    };
    const menus = state.menu
    const firstLevelMenu = {
        children: [],
        component: loadView('home/HomeView.vue')
    }
    menus.forEach(menu=>{
        menu.component = loadView(menu.component)
        if(menu.children === null || menu.children.length === 0){
            firstLevelMenu.children.push(menu)
        }else{
            menu.children.forEach(children=>{
                children.component = loadView(children.component)
            })
            router.addRoute(menu)
        }
    })
    router.addRoute(firstLevelMenu)
}

完成这些配置之后,路由就能动态加载了,然后取出vuex中存储的menu生成el-menu
\"\"
vuex中菜单大致如图

<el-menu
    router
    active-text-color="#ffd04b"
    background-color="#000"
    class="el-menu-vertical-demo"
    :default-active="this.$route.path"
    text-color="#fff"
    @open=""
    @close=""
>
  <template v-for="route of this.$store.state.menu">
    <template v-if="route.children === null || route.children.length === 0"><!--一级菜单-->
      <template v-if="!route.isHidden">
        <el-menu-item :index = "route.path">
          <span>{{route.name}}</span>
        </el-menu-item>
      </template>
    </template>
    <template v-else><!--二级菜单-->
      <template v-if="!route.isHidden">
        <el-sub-menu :index = "route.path">
          <template #title>
            <span>{{route.name}}</span>
          </template>
          <template v-for="children of route.children">
            <template v-if="!children.isHidden">
              <el-menu-item :index = "children.path">
                <span>{{children.name}}</span>
              </el-menu-item>
            </template>
          </template>
        </el-sub-menu>
      </template>
    </template>
  </template>
</el-menu>

实现效果展示
\"在这里插入图片描述\"
\"在这里插入图片描述\"

ItVuer - 免责声明 - 关于我们 - 联系我们

本网站信息来源于互联网,如有侵权请联系:561261067@qq.com

桂ICP备16001015号