vue、react 权限路由控制
A、vue权限控制
1、vue权限控制-- 路由鉴权,菜单动态渲染,自定义指令渲染按钮,递归处理数据
main.js中的路由守卫
router.beforeEach((to, from ,next)=>{
if(!store.state.token) {
if(to.matched.length > 0 && to.matched[to.matched.length - 1].meta.requireAuth) {
// console.log("不需要登录")
next()
}else{
// console.log("需要登录");
if(to.path == '/login') {
next();
}else{
next("/login")
}
}
}else{
if(!store.state.permissionList) {
// 登录过了,没有权限列表, 请求获取权限列表
store.dispatch("SET_PERMISSION").then(()=>{
next({
path: to.fullPath
})
})
}else{
console.log("登录过, 已经有权限列表了")
if(to.path != '/login') {
next();
}else{
next(from.fullPath)
}
}
}
})
路由表中根部暴露出来的路由(实际按自己的路由表写)
export const rootRoutes = [
{
path: '/',
name:'Layout',
component: ()=>import("@/views/layout"),
link: '/',
meta: {
requireAuth: false,
name: 'wrap'
},
children: [
{
path: 'scholl',
name: 'Scholl',
component: ()=>import("@/views/layout/views/scholl/index.vue"),
link: '/scholl',
meta: {
requireAuth: true,
name: '学校'
},
children: [
{
path: 'addScholl',
name: 'AddScholl',
link: '/scholl/addScholl',
component: ()=>import("@/views/layout/views/scholl/views/addScholl/index.vue"),
meta: {
requireAuth: false,
name: '新增学校'
},
},
{
path: 'deleteScholl',
name: 'DeleteScholl',
link: '/scholl/deleteScholl',
component: ()=>import("@/views/layout/views/scholl/views/deleteScholl/index.vue"),
meta: {
requireAuth: true,
name: '删除学校'
}
}
]
},
{
path: 'class',
name: 'Class',
link: '/class',
component: ()=>import("@/views/layout/views/class/index.vue"),
meta: {
requireAuth: false,
name: '班级'
},
children: [
{
path: 'addClass',
name: 'AddClass',
link: '/class/addClass',
component: ()=>import("@/views/layout/views/class/addClass/index.vue"),
meta: {
requireAuth: false,
name: '新增班级'
}
},
{
path: 'deleteClass',
name: 'DeleteClass',
link: '/class/deleteClass',
component: ()=>import("@/views/layout/views/class/deleteClass/index.vue"),
meta: {
requireAuth: true,
name: '删除班级'
}
}
]
}
]
},
// {
// path: '*',
// component: ()=>import("@/views/404")
// }
];
store中的state
export default {
// token
get token() {
return sessionStorage.getItem("token")
},
set token(value) {
sessionStorage.setItem("token", value);
},
// 权限列表
permissionList: null,
// 菜单列表
menuList: []
}
mutation
export default {
// 设置token
SET_TOKEN(state, token) {
state.token = token;
},
// 清空token
CLEAR_TOKEN(state) {
state.token = "";
},
// 设置权限列表
SET_PERMISSIONS(state, permissionList) {
state.permissionList = permissionList;
},
// 清空权限列表
CLEAR_PERMISSIONS(state) {
state.permissionList = null;
},
// 设置菜单列表
SET_MENUS(state, menuList) {
state.menuList = menuList;
},
// 清空菜单列表
CLEAR_MENUS(state, menuList) {
state.menuList = [];
}
}
action中
import {
permission } from "@/api"
import router, {
rootRoutes} from "@/router"
import {
recursionRouters, setDefau