vue项目动态router的实现

将router分为两类创建
  • 不受远程控制的路由
export const constantRoutes = [
        {
            path: '/404',
            name: '404',
            component: () =>
                import ('@/views/404'),
            hidden: true
        },
    ]

-受远程控制的路由

export const asyncRoutes = [
    {
           path: '/home',
           name: 'home',
           component: () =>
               import ('@/views/home'),
       },
        {
           path: '/test',
           name: 'test',
           component: () =>
               import ('@/views/test'),
       },
]
const router = new Router({
    routes: constantRoutes
})
// before 可不看,与动态router关系不大,
router.beforeEach(async(to, from, next) => {
	// 这儿要用async  因为菜单的权限是要从接口获取的 
next()

// 无论如何  next() 一定要有 不然router就不会渲染
// 当从定向时比如说,  next({
   //                 path: '/home'
   //             })  
   // 一定要在前面加上 if (to.path === '/login') { ...}之类的限制  不然会一直死循环 去到home页还会再去到home页
}
export default router
定义可显示的路由数组的nameList
const nameList = ['home',']
在vuex中对之前定义的asyncRoute进行筛选
import {
    asyncRoutes,
    constantRoutes
} from '@/router'

import router from '@/router';

const nameList = ['home']
const accessedRoutes = filterAsyncRoutes(asyncRoutes, nameList )
router.addRoutes([...accessedRoutes,
       ...constantRoutes
       ])

export function filterAsyncRoutes(routes, roles, metaObj) {
    const res = []
    routes.forEach(route => {
        const tmp = {
            ...route
        }
        if (roles.includes(tem.name)) {
            if (tmp.children) {
                tmp.children = filterAsyncRoutes(tmp.children, roles, metaObj)
            }
            res.push(tmp)
        }
    })

    return res
}

如果觉得这个不够清楚
可去往这儿
vue-router动态路由实现前端权限管理

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值