vue依据权限控制页面访问及生成动态路由

主体思路:依据 vue-router 提供的 addRoutes 实现路由的动态挂载

1、获取权限及对应路由的列表

权限字段由后端管理,并在登录时以数组形式返回权限列表

 

路由列表的话则类似下图,在路由元信息的 role 字段中定义当前页面组件对应的权限

2、依据后端返回的权限生成对应的路由表

设定一个验证当前路由对应权限是否包含于权限列表的方法

function roleListCheck(roleList, actions) {
    let haveRole = false
    roleList.forEach(item => {
        if (actions.includes(item)) {
            haveRole = true
        }
    })
    return haveRole
}

遍历所有的路由列表,生成我们所需要的路由表

export function setSyncRouter(data, origin) {
    let _data = data.toString()
    syncRouterList.forEach(item => {
        if (!item.meta.role || roleListCheck(item.meta.role, _data)) {
            return routerList.push(item)
        }
    })
    if (origin) {
        origin.addRoutes(routerList)
    } else {
        router.addRoutes(routerList)
    }
}

在登录时触发以上方法,并将权限列表存储于 localStorage 中,此后权限每次都在 localStorage 中获取

原文地址:https://www.cnblogs.com/yejunm3/p/14975568.html