router实例方法router.addRoutes

前端在做路由验证时,使用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

 

  • 1
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值