动态路由
-
准备好动态路由,用于匹配菜单动态添加路由
//动态路由,用于匹配菜单动态添加路由 const asyncRoutes = [ //商品管理 { path: '/goods/list', name: '/goods/list', component: () => import('@/pages/goods/GoodsList.vue'), meta: { title: '商品管理' } }, //后台首页 { path: '/', name: '/', component: () => import('@/pages/Index.vue'), meta: { title: '后台首页' } }, //分类页面 { path: '/category/list', name: '/category/list', component: () => import('@/pages/category/CategoryList.vue'), meta: { title: '分类管理' } }, ]
-
批量添加路由规则
1)通过提前定义好的【asyncRoutes】数组,找到菜单列表中的目标数组
2)判断菜单中书否存在该路由,并且该路由未被定义过
3)向根路由中添加子路由
4)在遍历菜单的时候判断是否存在子菜单
5)再一次通过递归的方式遍历
//批量添加路由 function addRoutes(menus) { //是否有新得路由 let hasNewRoutes = false const findAndAddRoutesByMenus = (arr) => { arr.forEach(e => { let item = asyncRoutes.find(o => o.path == e.frontpath) if (item && !router.hasRoute(item.path)) { router.addRoute('admin', item) hasNewRoutes = true } if (e.child && e.child.length > 0) { findAndAddRoutesByMenus(e.child) } }) } // 传入需要添加菜单列表 findAndAddRoutesByMenus(menus) return hasNewRoutes }
-
使用addRoute()方法之后,他们只注册一个新路由,如果新增路由与当前位置相匹配,就需要自己手动导航才能显示该新路由。
//前置路由守卫 router.beforeEach(async (to, from, next) => { if (!getToken() && to.path != '/login') { message('请先登录', 'warning') return next({ path: '/login' }) } if (getToken() && to.path == '/login') { message('您已经登录了', 'warning') return next({ path: from.path ? from.path : '/' }) } let hasNewRoutes = false if (getToken()) { let { menus } = await store.dispatch('getUserInfo') hasNewRoutes = addRoutes(menus) } //设置标题 document.title = to.meta.title ? to.meta.title : '后台管理系统' hasNewRoutes ? next(to.fullPath) : next() })