//主要靠路由守卫,中结合addRoute方法动态的添加一个新的路由列表
//pageRouterList为前端的所有权限列表
import Vue from 'vue'
import Router from 'vue-router'
import { constantRouterMap, asyncRouterMap } from '@/config/router.config'
import pageRouterList from './routers'
// hack router push callback
const originalPush = Router.prototype.push
Router.prototype.push = function push (location, onResolve, onReject) {
if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
return originalPush.call(this, location).catch((err) => err)
}
Vue.use(Router)
const router = new Router({
mode: 'hash',
routes: constantRouterMap.concat(asyncRouterMap)
})
var flag = false
// 挂载路由导航守卫,to表示将要访问的路径,from表示从哪里来,next是下一个要做的操作 next('/login')强制跳转login
router.beforeEach((to, from, next) => {
// 访问登录页,放行
if (to.path === '/login') return next()
// 获取token
const token = window.sessionStorage.getItem('token')
// 没有token, 强制跳转到登录页
if (!token) return next('/login')
//flag判断页面刷新,hasPeimiss判断是否从登录页面来的
if (!flag || JSON.parse(sessionStorage.getItem('hasPermiss')) === true) {
// 路由权限判断
flag = true
const menuList = pageRouterList
console.log(JSON.parse(sessionStorage.getItem('menuList')))
const netMenuList = JSON.parse(sessionStorage.getItem('menuList'))
if (netMenuList === null && netMenuList === undefined && netMenuList.length === 0) {
menuList[0].hidden = false
menuList[0].children[0].hidden = false
} else {
// 路由权限校验
netMenuList.forEach((e, index) => {
menuList.forEach((m, n) => {
// 第一层判断 菜单目录
if (e.funcType === 'DIR' && e.path === m.path) {
m.hidden = false
if (e.children.length > 0) {
// 第二层判断菜单页面
e.children.forEach((g, k) => {
m.children.forEach((l, p) => {
if (g.funcType === 'TAB' && g.path === l.path) {
l.hidden = false
if (g.children.length > 0) {
g.children.forEach((q, w) => {
// 第三层判断按钮权限
if (q.funcType === 'BTN') {
l.meta.power.push(q.path)
}
})
}
}
})
})
}
}
})
})
}
// 生成新的路由菜单 addRoute
router.matcher = new Router().matcher
asyncRouterMap[0].children = menuList
const allRouterList = constantRouterMap.concat(asyncRouterMap)
allRouterList.forEach((r) => {
router.addRoute(r)
})
// const myRoutes = router.getRoutes()
// console.log(myRoutes)
next({ ...to, replace: true })
} else {
next()
}
})
export default router
关于vue的路由权限
于 2022-06-06 17:35:02 首次发布