router实例方法router.addRoutes

燕寒
2023-12-01

前端在做路由验证时,使用router.Routes动态添加路由非常方便。

以下是后台返回的一组路由表,根据路由中的name字段判断此路由对应的组件是否显示:

import Vue from 'vue'
import VueRouter from 'vue-router'
import First from './components/first'
Vue.use(VueRouter)
const routers = [ // 首页不需要验证,相当于白名单
    {
        path: '/',
        component: First,
        name: 'first',
        meta: {title: 'first'}, // 路由原信息,这里用来动态设置网页标题
    }
]
const asyncRouters = [
    {
        path: '/sec',
        name: 'sec',
        component: () => import('./components/sec'),
        meta: {title: 'sec'},
        children: [
            {
                path: '/sec_son',
                name: 'sec_son',
                component: () => import('./components/sec_son'),
                meta: {title: 'sec_son'},
                children: [
                    {
                        path: '/sec_son_son',
                        name: 'sec_son_son',
                        meta: {title: 'sec_son_son'},
                        component: () => import('./components/sec_son_son'),
                    }
                ],
            }
        ]
    },
    {
        path: '/drag',
        name: 'drag',
        meta: {title: 'drag'},
        component: () => import('./components/vue-drags/drags')
    },
    {
        path: '/banner',
        name: 'banner',
        meta: {title: 'banner'},
        component: () => import('./components/banner/banner')
    },
    {
        path: '/edit',
        name: 'edit',
        meta: {title: 'edit'},
        component: () => import('./components/edit')
    },
    {
        path: '/debounce',
        name: 'debounce',
        meta: {title: 'debounce'},
        component: () => import('./components/debounce/debounce')
    }
]
const router = new VueRouter({
    routes: routers
})
// 假设下边asyncRouterList 是从后台获取的,里边参数与路由中的name对应
const asyncRouterList = ['debounce', 'sec', 'sec_son']
// 路由组合
function filterRoutes(routerss, myRouter) {
    const routesArr = []
    asyncRouters.forEach(item => {
        if(myRouter.includes(item['name'])) {
            if(item['children']) {
                // 递归组合路由
                item['children'] = filterRoutes(item['children'], myRouter)
            }
            routesArr.push(item)
        }
    })
    return routeSArr
}
// 使用addRoutes动态添加路由
router.addRoutes(filterRoutes(routerss, myRouter))
// 根据不同路由页,更改网页标题
router.beforeEach((from, to , next) => {
    if(to.meta.name) {
        document.title = to.meta.name
    }else {
        document.title = '默认标题'
    }
    next()
})
export default router

 

 类似资料: