menus.jsx 1.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import { Link } from 'react-router-dom';
  2. import { getPath } from './utils';
  3. // 菜单是否显示
  4. // 没有 meta 或者 meta.title 为空, 或者 meta.hideInMenu = true 的 都不显示
  5. const isShow = item => item.meta && item.meta.title && !item.meta.hideInMenu;
  6. const hasChildren = (list) => {
  7. if (!list || list.length < 1) return false;
  8. // 如果子元素全部都是不显示的, 说明子菜单不需要显示
  9. return list.filter(it => !isShow(it)).length !== list.length;
  10. }
  11. export const getMenuItems = (routes = [], fullPath = '/') => {
  12. return routes.map(route => {
  13. const path = getPath(fullPath, route.path);
  14. //
  15. if (!isShow(route)) return false;
  16. const children = hasChildren(route.children) ? getMenuItems(route.children, path) : false;
  17. const { target, title, icon } = route.meta || {}
  18. // 坑爹 react-router v6 不支持 hash 路由的 target 跳转
  19. const label = target === '_blank' ?
  20. <a href={`${window.location.pathname}${path}`} target={target}>{title}</a>
  21. : (
  22. path.indexOf('http') === 0 ? <a href={path} target="_blank">{title}</a>
  23. : <Link to={path} target={target}>{title}</Link>
  24. );
  25. return Object.assign(
  26. {
  27. key: path,
  28. label,
  29. title,
  30. icon,
  31. },
  32. children && { children },
  33. )
  34. }).filter(Boolean);
  35. }