Pro 模板中,菜单按照一定的约定进行配置,用来描述菜单栏的结构关系。以 BasicLayout 布局为例,菜单配置文件约定在 src/layouts/BasicLayout/menuConfig.ts中。

基本配置

菜单配置包含 headerMenuConfig 和 asideMenuConfig 两种形式,headerMenuConfig 用于顶部菜单栏的渲染,asideMenuConfig 用于侧边菜单栏的渲染,这样方便在统一的位置管理应用布局的菜单信息:

  1. // 顶部菜单栏配置
  2. export const headerMenuConfig = [
  3. {
  4. name: 'Home', // 菜单名称
  5. path: '/', // 菜单路径
  6. icon: 'message', // 菜单图标
  7. },
  8. ];
  9. // 侧边菜单栏配置
  10. export const asideMenuConfig = [
  11. {
  12. name: 'Dashboard', // 一级菜单名称
  13. path: '/', // 一级菜单路径
  14. icon: 'edit', // 一级菜单图标
  15. // 二级菜单配置
  16. children: [
  17. {
  18. name: 'Analysis', // 二级菜单名称
  19. path: '/dashboard/analysis', // 二级菜单路径
  20. },
  21. {
  22. name: 'DashboardChild',
  23. path: '/',
  24. icon: 'add',
  25. // 三级菜单配置
  26. children: [
  27. {
  28. name: 'Monitor', // 三级菜单名称
  29. path: '/dashboard/monitor', // 三级菜单路径
  30. },
  31. ],
  32. },
  33. ],
  34. },
  35. // ...
  36. ];

完整的菜单渲染逻辑可参考 src/layouts/BasicLayout/components/PageNav/index.tsx

菜单图标

我们默认使用 Icon 这个组件渲染图标,可以使用哪些图标可以在组件文档中看到,如果有其他自定义的图标需求,将代码改为对应图标组件即可。

  1. <SubNav key={item.name} icon={item.icon} label={item.name}>
  2. {childrenItems}
  3. </SubNav>

菜单权限

首先在 src/layouts/BasicLayout/menuConfig.ts 中增加以下的内容:

  1. export const asideMenuConfig = [
  2. {
  3. name: 'Home',
  4. path: '/',
  5. + auth: ['guest']
  6. },
  7. ];

然后在 src/layouts/BasicLayout/components/PageNav/index.tsx中配置以下内容:

  1. + import { useAuth } from 'ice';
  2. - function getNavMenuItems(menusData, initIndex) {
  3. + function getNavMenuItems(menusData, initIndex, auth) {
  4. - return menusData
  5. - .filter(item => item.name && !item.hideInMenu)
  6. - .map((item, index) => {
  7. - return getSubMenuOrItem(item, `${initIndex}-${index}`);
  8. - });
  9. + return menusData.filter(item => {
  10. + let roleAuth = true;
  11. + if (auth && item.auth && item.auth instanceof Array) {
  12. + if (item.auth.length) {
  13. + // 获取当前用户是否有该菜单的权限
  14. + roleAuth = item.auth.some(key => auth[key]);
  15. + }
  16. + }
  17. + return item.name && !item.hideInMenu && roleAuth;
  18. + }).map((item, index) => {
  19. + getSubMenuOrItem(item, `${initIndex}-${index}`, auth)
  20. + });
  21. }
  22. - function getSubMenuOrItem(item, index) {
  23. + function getSubMenuOrItem(item, index, auth) {
  24. if (item.children && item.children.some(child => child.name)) {
  25. - const childrenItems = getNavMenuItems(item.children, index);
  26. + const childrenItems = getNavMenuItems(item.children, index, auth);
  27. // ...
  28. }
  29. }
  30. const Navigation = () => {
  31. // 获取权限数据 更多权限管理的内容可以参考: https://ice.work/guide/advanced/auth.html
  32. + const [auth] = useAuth();
  33. return (
  34. <Nav embeddable activeDirection="right">
  35. - {getNavMenuItems(asideMenuConfig, 0)}
  36. + {getNavMenuItems(asideMenuConfig, 0, auth)}
  37. </Nav>
  38. )
  39. }

完整的菜单权限实现可参考 src/layouts/BasicLayout/components/PageNav/index.tsx