这是我参与更文挑战的第1天,活动详情查看:更文挑战css
一般咱们在vue项目中都是前端配置好路由的,但在一些项目中咱们可能会遇到权限控制,这样咱们就涉及到动态路由的设置了。前端
(1)、简单的角色路由设置: 好比只涉及到管理员和普通用户的权限。一般直接在前端进行简单的角色权限设置vue
(2)、复杂的路由权限设置: 好比OA系统、多种角色的权限配置。一般须要后端返回路由列表,前端渲染使用vue-router
(1)配置项目路由权限后端
// router.js
import Vue from 'vue'
import Router from 'vue-router'
import Layout from '@/layout'
Vue.use(Router)
let asyncRoutes = [
{
path: '/permission',
component: Layout,
redirect: '/permission/page',
alwaysShow: true,
name: 'Permission',
meta: {
title: 'Permission',
roles: ['admin', 'editor'] // 普通的用户角色
},
children: [
{
path: 'page',
component: () => import('@/views/permission/page'),
name: 'PagePermission',
meta: {
title: 'Page',
roles: ['editor'] // editor角色的用户才能访问该页面
}
},
{
path: 'role',
component: () => import('@/views/permission/role'),
name: 'RolePermission',
meta: {
title: 'Role',
roles: ['admin'] // admin角色的用户才能访问该页面
}
}
]
},
]
let router = new Router({
mode: 'history',
scrollBehavior: () => ({ y: 0 }),
routes: asyncRoutes
})
export default router
复制代码
// asyncRouter.js
//判断当前角色是否有访问权限
function hasPermission(roles, route) {
if (route.meta && route.meta.roles) {
return roles.some(role => route.meta.roles.includes(role))
} else {
return true
}
}
// 递归过滤异步路由表,筛选角色权限路由
export function filterAsyncRoutes(routes, roles) {
const res = [];
routes.forEach(route => {
const tmp = { ...route }
if (hasPermission(roles, tmp)) {
if (tmp.children) {
tmp.children = filterAsyncRoutes(tmp.children, roles)
}
res.push(tmp)
}
})
return res
}
复制代码
import router from './router'
import store from './store'
import NProgress from 'nprogress' // 进度条插件
import 'nprogress/nprogress.css' // 进度条样式
import { getToken } from '@/utils/auth'
import { filterAsyncRoutes } from '@/utils/asyncRouter.js'
NProgress.configure({ showSpinner: false }) // 进度条配置
const whiteList = ['/login']
router.beforeEach(async (to, from, next) => {
// 进度条开始
NProgress.start()
// 获取路由 meta 中的title,并设置给页面标题
document.title = to.meta.title
// 获取用户登陆的token
const hasToken = getToken()
// 判断当前用户是否登陆
if (hasToken) {
if (to.path === '/login') {
next({ path: '/' })
NProgress.done()
} else {
// 从store中获取用户角色
const hasRoles = store.getters.roles && store.getters.roles.length > 0
if (hasRoles) {
next()
} else {
try {
// 获取用户角色
const roles = await store.state.roles
// 经过用户角色,获取到角色路由表
const accessRoutes = filterAsyncRoutes(await store.state.routers,roles)
// 动态添加路由到router内
router.addRoutes(accessRoutes)
next({ ...to, replace: true })
} catch (error) {
// 清除用户登陆信息后,回跳到登陆页去
next(`/login?redirect=${to.path}`)
NProgress.done()
}
}
}
} else {
// 用户未登陆
if (whiteList.indexOf(to.path) !== -1) {
// 须要跳转的路由是不是whiteList中的路由,如果,则直接条状
next()
} else {
// 须要跳转的路由不是whiteList中的路由,直接跳转到登陆页
next(`/login?redirect=${to.path}`)
// 结束精度条
NProgress.done()
}
}
})
router.afterEach(() => {
// 结束精度条
NProgress.done()
})
复制代码
(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
复制代码
// 引入路由文件这种的公共路由
import { constantRoutes } from '../router';
// Layout 组件是项目中的主页面,切换路由时,仅切换Layout中的组件
import Layout from '@/layout';
export function getAsyncRoutes(routes) {
const res = []
// 定义路由中须要的自定名
const keys = ['path', 'name', 'children', 'redirect', 'meta', 'hidden']
// 遍历路由数组去重组可用的路由
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
}
复制代码
// 进度条引入设置如上面第一种描述同样
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()
})
复制代码
// 登陆接口调用后,调用路由接口,后端返回相应用户的路由res.router,咱们须要存储到store中,方便其余地方拿取
this.$store.dispatch("addRoutes", res.router);
复制代码
到这里,整个动态路由就能够走通了,可是页面跳转、路由守卫处理是异步的,会存在动态路由添加后跳转的是空白页面,这是由于路由在执行next()时,router里面的数据还不存在,此时,你能够经过
window.location.reload()
来刷新路由markdown
routerList = [
{
"path": "/other",
"component": "Layout",
"redirect": "noRedirect",
"name": "otherPage",
"meta": {
"title": "测试",
},
"children": [
{
"path": "a",
"component": "file/a",
"name": "a",
"meta": { "title": "a页面", "noCache": "true" }
},
{
"path": "b",
"component": "file/b",
"name": "b",
"meta": { "title": "b页面", "noCache": "true" }
},
]
}
]
复制代码
注意:vue是单页面应用程序,因此页面一刷新数据部分数据也会跟着丢失,因此咱们须要将store中的数据存储到本地,才能保证路由不丢失。关于vue页面刷新保存页面状态,能够查看 vue如何在页面刷新时保留状态信息cookie
人懒,不想配图,都是本身的博客内容(干货),望能帮到你们异步
公众号:小何成长,佛系更文,都是本身曾经踩过的坑或者是学到的东西async
有兴趣的小伙伴欢迎关注我哦,我是:小阿肥
。 你们一块儿进步鸭