一、页面权限控制
1)思路:在每一个路由的meta属性内,将能访问该路由的角色配置到roles内,用户登录的时候,返回用户的角色,在全局路由守卫内,把要跳转的路由的roles和用户的roles做下比对,,如果用户的roles包含在路由的roles内,则允许访问,否则不允许访问。
// 路由配置
routes: [ { path: '/login', name: 'login', meta: { roles: ['admin', 'user'] }, component: () => import('../components/Login.vue') }, { path: 'home', name: 'home', meta: { roles: ['admin'] }, component: () => import('../views/Home.vue') }, ]
// 路由守卫
// 获取到的用户角色信息
const userInfoRoles = ''
router.beforeEach((to, from, next) => { if (to.meta.roles.includes(userInfoRoles)) {
next()
} else {
next({path: '/404'})
}
})
2)思路:动态路由,根据用户登录后返回的信息,利用addRoutes添加动态路由,其中404页面放在路由最后。
const asyncRoutes = { 'home': { path: 'home', name: 'home', component: () => import('../views/Home.vue') }, 't1': { path: 't1', name: 't1', component: () => import('../views/T1.vue') }, 'password': { path: 'password', name: 'password', component: () => import('../views/Password.vue') }, 'msg': { path: 'msg', name: 'msg', component: () => import('../views/Msg.vue') }, 'userinfo': { path: 'userinfo', name: 'userinfo', component: () => import('../views/UserInfo.vue') } } // 传入后台数据 生成路由表 router.addRoutes(menusToRoutes(menusData))
// 将菜单信息转成对应的路由信息 动态添加 function menusToRoutes(data) { const result = [] const children = [] result.push({ path: '/', component: () => import('../components/Index.vue'), children, })
// 根据后台返回的用户权限的字段,在asyncRoutes内遍历取到符合要求的路由,添加到result内 /*data.forEach(item => { generateRoutes(children, item) })*/ children.push({ path: 'error', name: 'error', component: () => import('../components/Error.vue') }) // 最后添加404页面 否则会在登陆成功后跳到404页面 result.push( {path: '*', redirect: '/error'}, ) return result } /*function generateRoutes(children, item) { if (item.name) { children.push(asyncRoutes[item.name]) } else if (item.children) { item.children.forEach(e => { generateRoutes(children, e) }) } }*/
二、登录验证
思路:页面只需要登录一次,当第一次登录的时候,通过token或者cookie存入到本地,再次打开页面时,在全局路由守卫中先取token或cookie,没有的话则跳转到登录页
router.beforeEach((to, from, next) => { if (localStorage.getItem('token')) { if (to.path === '/login') {
// 已登录 next({path: '/'}) } else { next({path: to.path || '/'}) } } else { if (to.path === '/login') { next() } else { next(`/login?redirect=${to.path}`) } } })
asyncRoutes