Skip to content

Commit

Permalink
[add]页面权限控制
Browse files Browse the repository at this point in the history
  • Loading branch information
wuping committed Jan 26, 2024
1 parent 5bd9247 commit 80ca7d9
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 1 deletion.
51 changes: 51 additions & 0 deletions src/routers/auth.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@

const Auth = (props) => {
console.log(props, 'props')
let role = 'admin'
if (props.meta.role) {
if (!role.includes(props.meta.role)) {
return (
<div>没有权限</div>
)
}
}
return (
<>{props.children}</>
)
}

const authLoad = (element, meta = {}) => {
return <Auth meta={meta}>{element}</Auth>;
};

const transformRoutes = (routes) => {
let list = [];
routes.forEach((route) => {
const obj = { ...route };
if (obj.redirect) {
obj.element = <Navigate to={obj.redirect} replace={true} />;
}

if (obj.element) {
obj.element = authLoad(obj.element, obj.meta);
}

delete obj.redirect;
delete obj.meta;

if (obj.children) {
obj.children = transformRoutes(obj.children);
}
list.push(obj);
});
return list;
};




export {
Auth,
authLoad,
transformRoutes
}
9 changes: 8 additions & 1 deletion src/routers/guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import { useRoutes, useNavigate, useLocation } from 'react-router-dom'
import { useEffect } from 'react'
import { connect } from 'react-redux'
import { useSelector } from 'react-redux'
import { Auth, authLoad, transformRoutes } from './auth'

// 路由登录守卫
const Guard = (props) => {
const { token } = useSelector(state => state.loginReducer)
const navigate = useNavigate()//useNavigate钩子返回一个函数,这个hooks能够让我可以编程式的导航。
Expand All @@ -13,7 +16,11 @@ const Guard = (props) => {
navigate('/')
}
}, [location.pathname])
const outlet = useRoutes(props.router)

// 添加用户权限守卫
const outlet = useRoutes(
transformRoutes(props.router)
)
return outlet
}

Expand Down
13 changes: 13 additions & 0 deletions src/routers/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,25 @@ const routes = [
{
path: '/blogList',
element: lazyLoading(<Blog />),
meta:{
title: '博客列表',
role:['admin']
}
},
{
path: '/tagList',
element: lazyLoading(<Tag />),
meta:{
title: '标签列表'
}
},
{
path: '/test',
element: lazyLoading(<Test />),
meta:{
title: '测试',
role:['tester']
}
},
]
},
Expand All @@ -51,4 +62,6 @@ const routes = [
}
]



export default routes

0 comments on commit 80ca7d9

Please sign in to comment.