首先你要有两个路由表 一个是不管什么角色都能访问的路由表,还有一个是需要控制判断权限才能访问的路由表
公共路由表:
export const routes = [{
path: '/',
name: '',
redirect: '/login',
component: Login
},
{
path: '/login',
name: 'login',
component: Login
}
]
需要判断权限的路由表:
export const asyncRoutes = [{
path: '/index/system',
name: 'system',
component: () => import('@/pages/system'),
redirect: '/index/system/company/search',
meta: {
roles: ['admin']
},
children: [
{
path: '/index/system/client/search',
name: 'clientSearch',
meta: {
title: "Employee Query",
roles: ['admin']
},
{
path: '/index/system/company/search',
name: 'companySearch',
meta: {
title: "Company Query",
roles: ['admin']
},
component: () => import('@/pages/systemPages/companyMng/CompanySearch')
},
{
path: '/index/system/area/create',
name: 'areaCreate',
meta: {
title: "Area Create",
roles: ['admin']
},
component: () => import('@/pages/systemPages/areaMng/AreaCreate')
},
{
path: '/index/system/area/search',
name: 'areaSearch',
meta: {
title: "Area Query",
roles: ['admin']
},
component: () => import('@/pages/systemPages/areaMng/AreaSearch')
}
]
}]
可以在路由的meta里面设置一个roles属性来表示可以访问该路由的角色,以便于后期判断角色过滤路由表
然后就是最重要的就是router.before了
router.beforeEach(async(to, from, next) => {
const hasToken = getToken() //这里的方法 是获取用户token的方法 用来判断用户是否登录 由于是后台管理系统 所以应该把这个token存在sessionStorage里面比较安全
if (hasToken) { //这里判断该用户的登录状态 已经登录 那么进行下一步判断
if (to.path === '/login') { //如果该用户已经登录了 他又手贱去输入login页的路由 那么给他重点向到首页 记得登出的时候要清除登录标识!
next({ path: '/index' })
} else { //如果用户访问的不是login页那么进行下一步
const hasRoles = store.getters.roles && store.getters.roles.length > 0 //获取用户的角色 贮存在vuex中 每次刷新都是丢失 因为每次刷新router.addRoutes()也会失效 所以刚好重新获取角色重新 router.addRoutes()
if (hasRoles) { // 已经存在用户角色信息 那么也应该已经router.addRoutes()过了 所以直接放行 记得在首页登录的时候要存储用户权限和router.addRoutes() 感觉应该不用这么麻烦 但是先这样 后期再优化
next()
} else {//如果是没有权限信息的 那么要获取角色信息
try {
const { roles } = await store.dispatch('user/getInfo') //getInfo是一个拉取用户信息的接口 取得用户信息 并存到vuex中
const accessRoutes = await store.dispatch('permission/generateRoutes', roles) //generateRoutes是一个根据角色计算路由表的方法 返回一个根据用户角色筛选过后的路由表
router.addRoutes(accessRoutes) //添加路由表
next({ ...to, replace: true }) //由于再next() 之前 router.addRoutes()可能还未完成 所以这一步是确保 router.addRoutes()已经完成
} catch (error) { //这里就是一些接口报错之后的错误处理 我这边错误之后给他清楚了用户登录的标识 sessionStorage 然后再给他跳到首页
//这里写一些用户登出后的操作 清楚一些登录数据什么的
Message.error(error || 'Has Error')
next(`/login?redirect=${to.path}`)
}
}
}
} else { //如果用户没有登录 那他所有的跳转都给他重定向到首页
if (whiteList.indexOf(to.path) !== -1) { //路由白名单 防止死循环
next()
} else {
next(`/login?redirect=${to.path}`)
}
}
})
router index.js文件补充
import Vue from 'vue'
import Router from 'vue-router'
import { routes } from '@/router/routes'
Vue.use(Router)
const createRouter = () => new Router({
// mode: 'history', // require service support
scrollBehavior: () => ({ y: 0 }),
routes: routes
})
const router = createRouter()
router.selfaddRoutes = function (params){
router.matcher = new Router().matcher; //动态添加路由黄色报错去除的关键!!!!
router.addRoutes(params)
}
export default router
终于找到了去除黄色警报的方法 淦!!!