为了提高路由的管理,迅速感知到路由的变化,所以可以使用动态路由。简单来说,将写死的路由与原获取到的路由一一进行对比,为 true 该路由显示,否则不显示。
动态路由的写法
在router中的index.js中,将原本的路由写法进行拆分
原写法:
这里随便写一点小路径
const routes = [
{path:'/',component:admin,children:[
{path:'/',component:Index,meta:{title:'后台首页'}},
{path:'/goods/list',component:GoodList,meta:{title:'商品管理'}},
{path:'/category/list',component:CategoryList,meta:{title:'分类列表'}},
]},
{path:'/login',component:Login,meta:{title:'登录页'}},
{path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound},
]
const router = createRouter({
history: createWebHashHistory(),
routes
})
export default router
现在:
一般是将子路由进行动态添加,所以可以将子路由提出来,存放在数组中,比获取到的路径做判断。注意:共享的路径不需要提出,并且嵌套路由的父级需要加name。
const routes = [
{ path: '/', name:'admin', component: admin, }, //加name
{ path: '/login', component: Login, meta: { title: '登录页' } },
{ path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound },
]
// 动态路由,用于匹配菜单动态添加路由
const asyncRoutes = [
{ path: '/',name:'/', component: Index, meta: { title: '后台首页' } },
{ path: '/goods/list',name:'/goods/list', component: GoodList, meta: { title: '商品管理' } },
{ path: '/category/list',name:'/category/list', component: CategoryList, meta: { title: '分类列表' } },
]
动态添加路由
通过匹配中的路由,与异步获取的路由,进行对比,一致则显示
// 动态添加路由
export function addRoutes(menus){
// 判断是否有新的路由
let hasNewRoutes = false
// 通过递归来匹配asyncRoutes中的路由 与 异步获取菜单的路由,是否一致
const findAndAddRoutesByMenus = (arr)=>{
// 查找asyncRoutes路由 与 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
}