目录
源码实现:
// router 入参./router
// permissionList 有访问权限的路由的path的集合数组
// unCheck 不需要校验任何权限的path几何数组 比如 /404 /login 或者其他免登陆页面
// unPowerPath 无权限跳转的页面path
// unLoginPath 未登录跳转的页面path
// setLogin 用来设置登录状态
let isLogin: boolean = true
let _unLoginPath: string = ''
let _unPowerPath = ''
let _unCheck: string[] = []
let _router: any = {}
let _permissionList: string[] = []
interface PerParams {
router: any
permissionList: string[]
unCheck: string[]
unPowerPath: string
unLoginPath: string
}
const routerPermission = {
// 初始化路由鉴权插件
routerPermissionInit: function(data: PerParams) {
_unLoginPath = data.unLoginPath || '/login'
_unPowerPath = data.unPowerPath || '/404'
_permissionList = data.permissionList
_router = data.router
_unCheck = data.unCheck
// 防止未传值导致路由溢出
if (!_unCheck.includes(_unLoginPath)) {
_unCheck.push(_unLoginPath)
}
if (!_unCheck.includes(_unPowerPath)) {
_unCheck.push(_unPowerPath)
}
main()
},
setLogin: function(bool: boolean) {
isLogin = bool
},
setUnLoginPath: function(data: string) {
_unLoginPath = data
},
setUnPowerPath: function(data: string) {
_unPowerPath = data
},
setUnCheck: function(data: string[]) {
_unCheck = data
},
setPermissionList: function(data: string[]) {
_permissionList = data
},
setRouter: function(data: any) {
_router = data
}
}
function main(): void {
_router.beforeEach((to: any, from: any, next: any) => {
// 不需要权限和登录的白名单页面直接访问
if (_unCheck.includes(to.path)) {
next()
} else if (_permissionList.includes(to.path)) {
// 需授权限页面
// 已登录
if (isLogin) {
// 有授权也有登录
next()
} else {
// 有授权但未登录跳转指定页面或者默认登录页
next({ path: _unLoginPath || '/login' })
}
} else {
if (isLogin) {
// 登录状态下访问未授权页面跳转指定页面或者默认404
next({ path: _unPowerPath || '/404' })
} else {
// 未登录状态下访问未授权页面跳转指定页面或者默认登录页
next({ path: _unLoginPath || '/login' })
}
}
})
console.log('路由鉴权插件初始化成功')
}
export default routerPermission
引入方式:
### 功能:路由鉴权
### 使用方式
在main.js或者其他的主入口文件中引入
```js
import routerPermission from "@mtech/router-permission";
let permissionList = ["/two", "/", "/2", "/3"],
unCheck = ["/one","/4"],
unPowerPath = "/404",
unLoginPath = "/403";
routerPermission.routerPermissionInit({
router,// 自己工程完整的router.js暴露出的路有对象
permissionList,// 有访问权限的路由path路径的数组
unCheck,// 白名单数组
unPowerPath,// 在访问无权限的路由时跳转的页面,默认跳转'/404'
unLoginPath // 在未登录状态下访问跳转的页面,在有登录栈的工程中不需要用可不配置
});
// 另外可以在权限发生变化时,在工程的任意地方对路由的权限菜单进行配置
Vue.prototype.$routerPermission = routerPermission; // 绑定到Vue上
// 在其他地方均可调用修改参数的方法
setLogin(bool: boolean) {// 修改登录状态,有登录栈的工程中不需要用
isLogin = bool
},
setUnLoginPath(data: string) {// 有登录栈的工程中不需要用
_unLoginPath = data
},
setUnPowerPath(data: string) {// 设置访问无访问权限页面的跳转path
_unPowerPath = data
},
setUnCheck(data: string[]) {// 设置白名单
_unCheck = data
},
setPermissionList(data: string[]) {// 设置有权限的path数组
_permissionList = data
},
setRouter(data: any) {// 设置router
_router = data
}
```