vue2+antd——realizing dynamic menu routing function——basic accumulation


Recently when I was writing a backend management system, I encountered a need to change the previous static routing to dynamic routing. The backend framework used is: vue-antd-admin

Implementation requirements:

在页面开始登录时,通过路由接口可以获取到所有有权限的菜单数据。

Then use theloadRoutes method to implement asynchronous dynamic routing.

Rendering - The parameter rendering of the dynamic menu is as follows:

Insert image description here

Add the following code in the function inaccount.jsrefreshPermissions

As shown in the picture above, you need to write the following code after the login interface is called successfully:
import { loadRoutes } from '@/utils/routerUtil.js';
import { getCodeList } from '@/services/menu';//The interface for obtaining permissions. In my case, I go to Obtain the dynamic menu. In fact, this logic can be processed asynchronously.

actions: {
    
    
 refreshPermissions({
     
      commit }, callback) {
    
    
   getCodeList().then((res) => {
    
    
     let permissions = [];
     res &&
       res.map((x) => {
    
    
         permissions.push({
    
    
           id: x,
           operation: [],
         });
       });
     commit('setPermissions', permissions);
   });
   loadRoutes();
   callback && callback('success');
 }
}

loadRoutesThe method content is as follows:

import PageView from '@/layouts/PageView';
function changeRoutes(item) {
    
    
  let obj = {
    
     ...item };
  obj.component =
    item.routeTypeCode == 0
      ? PageView
      : (resolve) => require([`@/pages${
      
      item.component}`], resolve);
  if (item.children) {
    
    
    obj['children'] = item.children.map((child) => {
    
    
      return changeRoutes(child);
    });
  }
  return obj;
}
function loadRoutes(routesConfig){
    
    
  getCurrentMenu().then((arr) => {
    
    
  //如果接口没有数据,则可以用下面的模拟数据
  let arr = [
    {
    
    
      path: 'default',
      name: '工作台',
      icon: 'dashboard',
      component: '/dashboard/index',
      routeTypeCode: 1,
    },
    {
    
    
      path: '/memberManage',
      name: '客户管理',
      icon: 'team',
      component: '/BlankView',
      routeTypeCode: 0,
      children: [
        {
    
    
          path: '/company/list',
          name: '企业管理',
          component: '/Member/Company/list',
          routeTypeCode: 1,
        },
        {
    
    
          path: '/company/detail',
          name: '企业详情',
          invisible: true,
          routeTypeCode: 1,
          component: '/Member/Company/detail',
        },
        {
    
    
          name: '用户管理',
          path: '/member/list',
          routeTypeCode: 1,
          component: '/Member/Member/list',
        },
        {
    
    
          name: '用户详情',
          path: '/member/detail',
          routeTypeCode: 1,
          invisible: true,
          component: '/Member/Member/detail',
        },
      ],
    },
    {
    
    
      path: '/system',
      name: '系统管理',
      icon: 'setting',
      routeTypeCode: 0,
      component: () => import('@/layouts/PageView'),
      children: [
        {
    
    
          name: '角色管理',
          path: '/system/role',
          routeTypeCode: 1,
          component: '/identity/RoleList',
        },
        {
    
    
          name: '部门组织',
          path: '/system/organization',
          routeTypeCode: 1,
          component: '/organization/organizationUnits',
        },
        {
    
    
          name: '用户管理',
          path: '/system/user',
          routeTypeCode: 1,
          component: '/identity/UserList',
        },
        {
    
    
          name: '数据字典',
          path: '/system/dataDictionary',
          routeTypeCode: 1,
          component: '/dataDictionary/DataDictionary',
        },
        {
    
    
          name: '客户端管理',
          path: '/system/openApi',
          routeTypeCode: 1,
          component: '/OpenAPI/index',
        },
        {
    
    
          name: 'HttpApi日志',
          path: '/system/httpApi',
          routeTypeCode: 1,
          component: '/system/httpApi',
        },
        {
    
    
          name: '审计日志',
          path: '/system/auditLog',
          routeTypeCode: 1,
          component: '/system/auditLog',
        },
        {
    
    
          name: '缓存列表',
          path: '/system/cache',
          routeTypeCode: 1,
          component: '/system/cache',
        },
      ],
    },
    {
    
    
      path: '/menu',
      name: '菜单管理',
      icon: 'menu',
      routeTypeCode: 0,
      redirect: '/menu/list',
      component: '/BlankView.vue',
      children: [
        {
    
    
          path: '/menu/list',
          name: '菜单管理',
          routeTypeCode: 1,
          component: '/Menu/menuList.vue',
        },
      ],
    },
  ];
  let list = [];
  arr.forEach((item) => {
    
    
    if (item.routeTypeCode != 2) {
    
    
      list.push(changeRoutes(item));
    }
  });
  routesConfig = [
    {
    
    
      router: 'root',
      children: list,
    },
  ];
  console.log('加载路由了,在此处请求接口获取数据', routesConfig);
  // 应用配置
  const {
    
     router, store, i18n } = appOptions;
  // 如果 routesConfig 有值,则更新到本地,否则从本地获取
  if (routesConfig) {
    
    
    store.commit('account/setRoutesConfig', routesConfig);
  } else {
    
    
    routesConfig = store.getters['account/routesConfig'];
  }
  // 如果开启了异步路由,则加载异步路由配置
  // const asyncRoutes = store.state.setting.asyncRoutes;
  const asyncRoutes = true;
  if (asyncRoutes) {
    
    
    if (routesConfig && routesConfig.length > 0) {
    
    
      const routes = parseRoutes(routesConfig, routerMap);
      const finalRoutes = mergeRoutes(basicOptions.routes, routes);
      formatRoutes(finalRoutes);
      router.options = {
    
     ...router.options, routes: finalRoutes };
      router.matcher = new Router({
    
     ...router.options, routes: [] }).matcher;
      console.log('finalRoutes', finalRoutes);
      router.addRoutes(finalRoutes);
    }
  }
  // 提取路由国际化数据
  mergeI18nFromRoutes(i18n, router.options.routes);
  // 初始化Admin后台菜单数据
  const rootRoute = router.options.routes.find((item) => item.path === '/');
  const menuRoutes = rootRoute && rootRoute.children;
  if (menuRoutes) {
    
    
    store.commit('setting/setMenuData', menuRoutes);
  }
  })
}

The most important above

Guess you like

Origin blog.csdn.net/yehaocheng520/article/details/134117855