import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login'
import Layout from '@/Layout'
import { AUTH } from '../service/users'
import store from '../store'
// 解决多次跳转已激活链接报错 这是因为vue-router的bug导致的
/*
Avoided redundant navigation to current location: "/xxx"
*/
Vue.use(VueRouter)
const originalPush=VueRouter.prototype.push
VueRouter.prototype.push=function push(location){
return originalPush.call(this,location).catch(err=>err)
}
//循环引入
const _routes = []
const files = require.context('./routes', true, /\.js$/)
files.keys().forEach(path => {
const module = files(path).default
if (module) {
_routes.push({
component: Layout,
...module
})
}
})
// 基于roles对_routes进行过滤,删除掉没有权限的路由,只让有权限的路由生效
console.log(_routes)
// 声明一个过滤函数 递归做法,可以实现多层嵌套路由
/* const filterRoutes = (routes, roles, basePath = '') => {
const arr = []
routes.forEach(parentRoute => {
// 如果权限数组中包含当前遍历的path
if (roles.includes(basePath + parentRoute.path)) {
const route = {
...parentRoute,
// children: []
}
// 如果有children
if (parentRoute.children && parentRoute.children.length > 0) {
route.children = filterRoutes(parentRoute.children, roles, parentRoute.path + "/")
}
// 拥有权限则添加到数组arr里
arr.push(route)
}
})
return arr
} */
// 只能实现两层的路由嵌套 把现有前端的路由,和后台返回的权限信息进行对应的对比,将不符合条件的路由给剔除,得到所有符合条件的路由
export const filterRoutes = (routes, roles) => {
const arr = []
routes.forEach(parentRoute => {
if (roles.includes(parentRoute.name)) {
const route = {
...parentRoute,
children: []
}
if (parentRoute.children && parentRoute.children.length) {
parentRoute.children.forEach(childRoute => {
if (roles.includes(childRoute.name)) {
// 如果有,则添加到children数组中
route.children.push(childRoute)
}
})
}
// 拿着parentRoute加入到新的数组中
arr.push(route)
}
})
return arr
}
let menuRoutes = _routes
// 判断是否登录,如果登录则拿着roles进行路由的筛选
/*
页面刷新后对应的menu组件中渲染最新的菜单路由
*/
if (localStorage.getItem('user')) {
const roles = JSON.parse(localStorage.getItem('user')).roles
const _menuRoutes = filterRoutes(_routes, roles)
console.log(menuRoutes)
// 把menuRoutes 设置给 vuex
// this.$store.commit()
store.commit('setRoutes', _menuRoutes)
}
const routes = [
{
path: '/',
redirect: '/dashboard'
},
{
path: '/login',
component: Login
},
{
path: '/403',
component: () => import('@/views/Error/404')
},
...menuRoutes,
{
path: '*',
component: () => import('@/views/Error/404')
}
]
const router = new VueRouter({
mode: "history",
routes
})
/*
定义路由的导航守卫-全局前置守卫
*/
router.beforeEach((to, from, next) => {
// 如果我们跳转的不是登录/login,则跳转到登录
if (to.path !== '/login' && to.path !== '/403') {
// 进行路由的拦截,拦截to.path, 查看to.path是否在roles
if (localStorage.getItem('user')) {
const roles = JSON.parse(localStorage.getItem('user')).roles
if (!roles.includes(to.name)) {
next('/403')
return
}
}
// 判断token是否存在,并且是否正确
const token = localStorage.getItem('token')
if (token) {
AUTH().then(() => {
next()
})
} else {
next('/login')
}
} else {
next()
}
})
export {
menuRoutes
}
export default router
验证鉴权mm
最新推荐文章于 2024-06-22 16:16:57 发布