动态路由与持久化更新

为了提高路由的管理,迅速感知到路由的变化,所以可以使用动态路由。简单来说,将写死的路由与原获取到的路由一一进行对比,为 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
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值