Ant Design Pro 动态路由的实现

  • 提供登录与获取用户信息数据接口

在这里插入图片描述

import request from '@/utils/request';

/**
 * 
 * @returns 首页列表权限
 */
export async function queryCurrent():Promise<any>{
  return request('/user/info2', {
    prefix:'/mock',
    method: 'GET',
  });
}
登录接口数据
{'code': 200, 'data': {'token': 'X-admin'}, 'message': "操作成功"}

详情接口数据
{
    "code": 200,
    "data": {
        "avatar": "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
        "name": "黄晓果",
        "roles": [
            "editor"
        ]
    }
}

  • 修改models/user.ts
export type CurrentUser = {
  avatar?: string;
  name?: string;
  introduction?: string;
  roles?: string | string[];
};


 effects: {
    *fetchCurrent(_, { call, put }) {
      const response = yield call(queryCurrent);
      yield put({
        type: 'saveCurrentUser',
        payload: response.data,
      });
    },
  },
import type { Effect, Reducer } from 'umi';

import { queryCurrent } from '@/services/user';

export type CurrentUser = {
  avatar?: string;
  name?: string;
  introduction?: string;
  roles?: string | string[];
};

export type UserModelState = {
  currentUser?: CurrentUser;
};

export type UserModelType = {
  namespace: 'user';
  state: UserModelState;
  effects: {
    fetchCurrent: Effect;
  };
  reducers: {
    saveCurrentUser: Reducer<UserModelState>;
  };
};

const UserModel: UserModelType = {
  namespace: 'user',

  state: {
    currentUser: {},
  },

  effects: {
    *fetchCurrent(_, { call, put }) {
      const response = yield call(queryCurrent);
      yield put({
        type: 'saveCurrentUser',
        payload: response.data,
      });
    },
  },

  reducers: {
    saveCurrentUser(state, action) {
      return {
        ...state,
        currentUser: action.payload || {},
      };
    },
  },
};

export default UserModel;

  • 改造config/routes.ts
export default [
  {
    path: '/',
    component: '../layouts/BlankLayout',
    routes: [
      {
        path: '/user',
        component: '../layouts/UserLayout',
        routes: [
          {
            name: '登录',
            path: '/user/login',
            component: './User/login',
          },
          {
            component: './404',
          },
        ],
      },
      {
        path: '/',
        component: '../layouts/SecurityLayout',
        routes: [
          {
            path: '/',
            component: '../layouts/BasicLayout',
            routes: [
              {
                path: '/',
                redirect: '/welcome',
              },
              {
                path: '/welcome',
                component: './Welcome',
              },
              {
                path: '/Usermanage',
                icon: 'form',
                name: '用户管理',
                authority: ['admin'],
                routes: [
                  {
                    path: '/',
                    redirect: '/usermanage/rolemanage',
                  },
                  {
                    name: '角色管理',
                    icon: 'form',
                    path: '/usermanage/rolemanage',
                    component: './Usermanage/rolemanage',
                    authority: ['admin'],
                  },
                  {
                    name: '账号列表',
                    icon: 'form',
                    path: '/usermanage/accountlist',
                    component: './Usermanage/accountlist',
                    authority: ['admin'],
                  },
                ],
              },
              {
                path: '/voicemanage',
                icon: 'form',
                name: '语音管理',
                authority: ['admin'],
                routes: [
                  {
                    path: '/',
                    redirect: '/voicemanage/albumscategories',
                  },
                  {
                    name: '专辑分类',
                    icon: 'form',
                    path: '/voicemanage/albumscategories',
                    component: './voicemanage/albumscategories',
                  },
                  {
                    name: '收听管理',
                    icon: 'form',
                    path: '/voicemanage/listenmanage',
                    component: './voicemanage/listenmanage',
                  },
                ],
              },
              {
                path: '/appmanagement',
                icon: 'form',
                name: 'App管理',
                routes: [
                  {
                    path: '/',
                    redirect: '/appmanagement/banner',
                  },
                  {
                    name: 'Banner管理',
                    icon: 'form',
                    path: '/appmanagement/banner',
                    component: './appmanagement/banner',
                  },
                  {
                    name: 'App版本管理',
                    icon: 'form',
                    path: '/appmanagement/appversions',
                    component: './appmanagement/appversions',
                  },
                ],
              },
              {
                path: '/vipmanagement',
                icon: 'form',
                name: 'VIP管理',
                authority: ['admin'],
                routes: [
                  {
                    path: '/',
                    redirect: '/vipmanagement/setmeal',
                  },
                  {
                    name: '套餐管理',
                    icon: 'form',
                    path: '/vipmanagement/setmeal',
                    component: './vipmanagement/setmeal',
                    authority: ['admin'],
                  },
                  {
                    name: '激活码管理',
                    icon: 'form',
                    path: '/vipmanagement/activationcode',
                    component: './vipmanagement/activationcode',
                    authority: ['admin'],
                  },
                  {
                    name: '激活码生成列表',
                    icon: 'form',
                    path: '/vipmanagement/activationcodelist',
                    component: './vipmanagement/activationcodelist',
                    authority: ['admin'],
                  },
                  {
                    name: '激活码导出列表',
                    icon: 'form',
                    path: '/vipmanagement/activationcodeexport',
                    component: './vipmanagement/activationcodeexport',
                    authority: ['admin'],
                  },
                  {
                    name: '订单列表',
                    icon: 'form',
                    path: '/vipmanagement/orderlist',
                    component: './vipmanagement/orderlist',
                    authority: ['admin'],
                  },
                  {
                    name: 'VIP权益说明',
                    icon: 'form',
                    path: '/vipmanagement/vipequity',
                    component: './vipmanagement/vipequity',
                    authority: ['admin'],
                  },
                ],
              },
              {
                path: '/brandownermanage',
                icon: 'form',
                name: '品牌商管理',
                authority: ['admin'],
                routes: [
                  {
                    path: '/',
                    redirect: '/brandownermanage/brandownerlist',
                  },
                  {
                    name: '品牌商列表',
                    icon: 'form',
                    path: '/brandownermanage/brandownerlist',
                    component: './brandownermanage/brandownerlist',
                    authority: ['admin'],
                  },
                ],
              },
              {
                path: '/machinemanage',
                icon: 'form',
                name: '机器管理', authority: ['admin'],
                routes: [
                  {
                    path: '/',
                    redirect: '/machinemanage/machinelist',
                  },
                  {
                    name: '机器列表',
                    icon: 'form',
                    path: '/machinemanage/machinelist',
                    component: './machinemanage/machinelist',
                    authority: ['admin'],
                  },
                ],
              },
              {
                path: '/softwaremanage',
                icon: 'form',
                name: '软件管理',
                authority: ['user'],
                routes: [
                  {
                    path: '/',
                    redirect: '/softwaremanage/versions',
                  },
                  {
                    name: '版本管理',
                    icon: 'form',
                    path: '/softwaremanage/versions',
                    component: './softwaremanage/versions',
                    authority: ['admin'],
                  },
                  {
                    name: '使用说明',
                    icon: 'form',
                    path: '/softwaremanage/usedirection',
                    component: './softwaremanage/usedirection',
                    authority: ['admin'],
                  },
                ],
              },
              {
                path: '/officialaccounts',
                icon: 'form',
                name: '公众号设置',
                authority: ['user'],
                routes: [
                  {
                    path: '/',
                    redirect: '/officialaccounts/accesssettings',
                  },
                  {
                    name: '接入设置',
                    icon: 'form',
                    path: '/officialaccounts/accesssettings',
                    component: './officialaccounts/accesssettings',
                    authority: ['admin'],
                  },
                  {
                    name: '菜单设置',
                    icon: 'form',
                    path: '/officialaccounts/menu',
                    component: './officialaccounts/menu',
                    authority: ['admin'],
                  }, {
                    name: '关注回复',
                    icon: 'form',
                    path: '/officialaccounts/attentionreply',
                    component: './officialaccounts/attentionreply',
                    authority: ['admin'],
                  }, {
                    name: '关键字回复',
                    icon: 'form',
                    path: '/officialaccounts/keywordreply',
                    component: './officialaccounts/keywordreply',
                    authority: ['admin'],
                  }, {
                    name: '素材管理',
                    icon: 'form',
                    path: '/officialaccounts/material',
                    component: './officialaccounts/material',
                    authority: ['admin'],
                  },
                ],
              },
              {
                component: './404',
              },
            ],
          },
          {
            component: './404',
          },
        ],
      },
    ],
  },
  {
    component: './404',
  },
];

将动态显示的路由填写authority 例如: authority: [‘admin’],

  • 修改layouts/SecurityLayout.tsx
    在这里插入图片描述
import {setAuthority} from '@/utils/authority'
	// You can replace it to your authentication rule (such as check token exists)
    // 你可以把它替换成你自己的登录认证规则(比如判断 token 是否存在)
    /**
     * 这里要注意替换否则进不来主页面
     */
const isLogin = currentUser && currentUser.name;
setAuthority(currentUser?.roles)
import React from 'react';
import { PageLoading } from '@ant-design/pro-layout';
import type { ConnectProps } from 'umi';
import { Redirect, connect } from 'umi';
import { stringify } from 'querystring';
import type { ConnectState } from '@/models/connect';
import type { CurrentUser } from '@/models/user';
import {setAuthority} from '@/utils/authority'

type SecurityLayoutProps = {
  loading?: boolean;
  currentUser?: CurrentUser;
} & ConnectProps;

type SecurityLayoutState = {
  isReady: boolean;
};

class SecurityLayout extends React.Component<SecurityLayoutProps, SecurityLayoutState> {
  state: SecurityLayoutState = {
    isReady: false,
  };

  componentDidMount() {
    this.setState({
      isReady: true,
    });
    const { dispatch } = this.props;
    if (dispatch) {
      dispatch({
        type: 'user/fetchCurrent',
      });
    }
  }

  render() {
    const { isReady } = this.state;
    const { children, loading, currentUser } = this.props;
    // You can replace it to your authentication rule (such as check token exists)
    // 你可以把它替换成你自己的登录认证规则(比如判断 token 是否存在)
    /**
     * 这里要注意替换否则进不来主页面
     */
    const isLogin = currentUser && currentUser.name;
    setAuthority(currentUser?.roles)
    const queryString = stringify({
      redirect: window.location.href,
    });

    if ((!isLogin && loading) || !isReady) {
      return <PageLoading />;
    }
    if (!isLogin && window.location.pathname !== '/user/login') {
      return <Redirect to={`/user/login?${queryString}`} />;
    }
    return children;
  }
}

export default connect(({ user, loading }: ConnectState) => ({
  currentUser: user.currentUser,
  loading: loading.models.user,
}))(SecurityLayout);

  • 修改utils/authority.ts
export function setAuthority(authority: string | string[]|undefined): void {
  const proAuthority = typeof authority === 'string' ? [authority] : authority;
  localStorage.setItem('antd-pro-authority', JSON.stringify(proAuthority));
  // auto reload
  reloadAuthorized();
}
import { reloadAuthorized } from './Authorized';

// use localStorage to store the authority info, which might be sent from server in actual project.
export function getAuthority(str?: string): string | string[] {
  const authorityString =
    typeof str === 'undefined' && localStorage ? localStorage.getItem('antd-pro-authority') : str;
  // authorityString could be admin, "admin", ["admin"]
  let authority;
  try {
    if (authorityString) {
      authority = JSON.parse(authorityString);
    }
  } catch (e) {
    authority = authorityString;
  }
  if (typeof authority === 'string') {
    return [authority];
  }
  // preview.pro.ant.design only do not use in your production.
  // preview.pro.ant.design 专用环境变量,请不要在你的项目中使用它。
  if (!authority && ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site') {
    return ['admin'];
  }
  return authority;
}

export function setAuthority(authority: string | string[]|undefined): void {
  const proAuthority = typeof authority === 'string' ? [authority] : authority;
  localStorage.setItem('antd-pro-authority', JSON.stringify(proAuthority));
  // auto reload
  reloadAuthorized();
}

Pro 扩展路由配置

  • name: 当前路由在菜单和面包屑中的名称,注意这里是国际化配置的 key,具体展示菜单名可以在 /src/locales/zh-CN.js 进行配置。
  • icon: 当前路由在菜单下的图标名。
  • hideInMenu: 当前路由在菜单中不展现,默认 false。
  • hideChildrenInMenu: 当前路由的子级在菜单中不展现,默认 false。
  • hideInBreadcrumb: 当前路由在面包屑中不展现,默认 false。
  • authority: 允许展示的权限,不设则都可见,详见:权限管理。
{
  name: 'dashboard',
  icon: 'dashboard',
  hideInMenu: true,
  hideChildrenInMenu: true,
  hideInBreadcrumb: true,
  authority: ['admin'],
}

相关推荐
©️2020 CSDN 皮肤主题: Age of Ai 设计师:meimeiellie 返回首页