赞
踩
1、我在登陆时获取到登录用户的角色名roles,并存入sessionStorage中,具体是在login页面实现,还是在menu页面实现都可以。在menu页面实现,可以显得登陆快一些。
2、编写router.js,注意,一个用户可能有多个角色。
//以下为一个路由例子
{
path: "/xxxx/xxxx",
component: () => import('@/components/xxx'),
name: "随便取个名字",
meta: {
roles:['角色1','角色2','角色3']
}
}
//在路由跳转前进行判断 router.beforeEach((to,from,next) => { //设置直接通过的路由地址 if(to.path === "/" || to.path === "/login" || to.path === "/menu") { next(); }else { const tokenStr = localStorage.getItem("token") //如果token没有了,直接返回登录界面,即长时间没有操作。 if (!tokenStr) { return next("/login"); }else { //数据库中的roles以“角色1,角色2,角色3”的字符串存储,使用split分割成数组 const roles = sessionStorage.getItem("userRole").split(",") //这里表示路由设置的roles中内有内容,我们没有设置权限,那么直接放行。 if(to.meta.roles.length === 0){ next() }else{ //这里表示做循环,只要有一个满足就可以跳转了。 for (let i = 0; i < to.meta.roles.length; i++){ //roles中有一个与用于的角色匹配就行 if(roles.includes(to.meta.roles[i])){ next() } } } } }
我们的roles存在sessionStorage中,关闭那个网页就没有了。但是token还在,就会产生报错,我们做一下判断最好。或者把roles也存在localstorage中
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。