复杂的路由权限设置: 比如OA系统、多种角色的权限配置。通常需要后端返回路由列表,前端渲染使用
1)配置项目路由文件,该文件中没有路由,或者存在一部分公共路由,即没有权限的路由
import Vue from 'vue'
import Router from 'vue-router'
import Layout from '@/layout';
Vue.use(Router)
// 配置项目中没有涉及权限的公共路由
export const constantRoutes = [
{
path: '/login',
component: () => import('@/views/login'),
hidden: true
},
{
path: '/404',
component: () => import('@/views/404'),
hidden: true
},
]
const createRouter = () => new Router({
mode: 'history',
scrollBehavior: () => ({ y: 0 }),
routes: constantRoutes
})
const router = createRouter()
export function resetRouter() {
const newRouter = createRouter()
router.matcher = newRouter.matcher
}
export default router
2)新建一个公共的asyncRouter.js文件
// 引入路由文件这种的公共路由
import { constantRoutes } from '../router';
// Layout 组件是项目中的主页面,切换路由时,仅切换Layout中的组件
import Layout from '@/layout';
export function getAsyncRoutes(routes) {
const res = []
// 定义路由中需要的自定名
const keys = ['path', 'name', 'children', 'redirect', 'meta', 'hidden','alwaysShow']
// 遍历路由数组去重组可用的路由
routes.forEach(item => {
const newItem = {};
if (item.component) {
// 判断 item.component 是否等于 'Layout',若是则直接替换成引入的 Layout 组件
if (item.component === 'Layout') {
newItem.component = Layout
} else {
// item.component 不等于 'Layout',则说明它是组件路径地址,因此直接替换成路由引入的方法
newItem.component = resolve => require([`@/views/${item.component}`],resolve)
// 此处用reqiure比较好,import引入变量会有各种莫名的错误
// newItem.component = (() => import(`@/views/${item.component}`));
}
}
for (const key in item) {
if (keys.includes(key)) {
newItem[key] = item[key]
}
}
// 若遍历的当前路由存在子路由,需要对子路由进行递归遍历
if (newItem.children && newItem.children.length) {
newItem.children = getAsyncRoutes(item.children)
}
res.push(newItem)
})
// 返回处理好且可用的路由数组
return res
}
3)创建路由守卫:创建公共的permission.js文件,设置路由守卫
// 进度条引入设置如上面第一种描述一样
import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import { getAsyncRoutes } from '@/utils/asyncRouter'
const whiteList = ['/login'];
router.beforeEach( async (to, from, next) => {
NProgress.start()
document.title = to.meta.title;
// 获取用户token,用来判断当前用户是否登录
const hasToken = getToken()
if (hasToken) {
if (to.path === '/login') {
next({ path: '/' })
NProgress.done()
} else {
//异步获取store中的路由
let route = await store.state.addRoutes;
const hasRouters = route && route.length>0;
//判断store中是否有路由,若有,进行下一步
if ( hasRouters ) {
next()
} else {
//store中没有路由,则需要获取获取异步路由,并进行格式化处理
try {
const accessRoutes = getAsyncRoutes(await store.state.addRoutes );
// 动态添加格式化过的路由
router.addRoutes(accessRoutes);
next({ ...to, replace: true })
} catch (error) {
// Message.error('出错了')
next(`/login?redirect=${to.path}`)
NProgress.done()
}
}
}
} else {
if (whiteList.indexOf(to.path) !== -1) {
next()
} else {
next(`/login?redirect=${to.path}`)
NProgress.done()
}
}
})
router.afterEach(() => {
NProgress.done()
})
4)在main.js中引入permission.js文件
5)在login登录的时候将路由信息存储到store中
// 登录接口调用后,调用路由接口,后端返回相应用户的路由res.router,我们需要存储到store中,方便其他地方拿取
this.$store.dispatch("addRoutes", res.router);
到这里,整个动态路由就可以走通了,但是页面跳转、路由守卫处理是异步的,会存在动态路由添加后跳转的是空白页面,这是因为路由在执行next()时,router里面的数据还不存在,此时,你可以通过window.location.reload()来刷新路由
6).后端返回的路由格式:
"responseData": [{
"path": "/org",
"component": "org",
"redirect": "noRedirect",
"alwaysShow": true,
"name": "org",
"meta": {
"title": "组织架构中心",
"icon": "icon"
},
"children": [{
"path": "/person",
"component": "personnel",
"redirect": "noRedirect",
"alwaysShow": true,
"name": "personnel",
"meta": {
"title": "人事管理",
"icon": ""
},
"children": [{
"path": "/manage",
"component": "recruitManagement/recruitManagement",
"redirect": "noRedirect",
"name": "personnel_recruit_list",
"meta": {
"title": "招聘管理",
"icon": ""
}
}, {
"path": "/order",
"component": "dispatchrequirement/dispatchRequirementList",
"redirect": "noRedirect",
"name": "dispatch_requirement_list",
"meta": {
"title": "派单需求",
"icon": ""
}
}]
}]
}],
```
![在这里插入图片描述](https://img-blog.csdnimg.cn/a3fb528e9c014e5489f892e189441746.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5q-b5bCW5ZOl,size_13,color_FFFFFF,t_70,g_se,x_16)