pure-admin框架动态路由实战,如何处理动态路由,代码片段

发布时间:2024年01月22日

?只在文章上粘贴了自己改的地方,原作者添加的就不粘贴了,本文主要展示的为utils.ts文件

pure-admin官方文档链接:点击跳转

动态路由处理:

 const newList = [];
  for (let i = 0; i < newArray.length; i++) {
    if (newArray[i][KEY_PID] === KEY_PARENTID) {
      //获取最顶层元素,它的父节点ID=0
      newList.push(newArray[i]);
    } else {
      const parent = newArray.find(item => {
        return item[KEY_ID] === newArray[i][KEY_PID];
      }); // 获取当前节点的父节点

      if (parent) {
        // 把当前节点 加入到 父节点中
        if (parent[KEY_CHILDREN]) {
          parent[KEY_CHILDREN].push(newArray[i]);
        } else {
          parent[KEY_CHILDREN] = [newArray[i]];
        }
      }
    }
  }
  return newList;
}
/** 处理动态路由(后端返回的路由) */
function handleAsyncRoutes(routeList) {
  console.log(routeList);
  
  let one = formatFlatteningRoutes(routeList).map(val => {
    delete val.children;
    return val;
  });
  console.log(cloneDeep(one));

  const modulesRoutesKeys = Object.keys(modulesRoutes);
  let arr = one.filter(
    val => modulesRoutesKeys.findIndex(ev => ev.includes(val.path)) > -1
  );
  console.log(arr);

  let newList = arrayToTree(arr);
  console.log(newList);
  if (routeList.length === 0) {
    usePermissionStoreHook().handleWholeMenus(routeList);
  } else {
    formatFlatteningRoutes(addAsyncRoutes(newList)).map(
      (v: RouteRecordRaw) => {
        console.log(router.options.routes);

        // 防止重复添加路由
        if (
          router.options.routes[0].children.findIndex(
            value => value.path === v.path
          ) !== -1
        ) {
          return;
        } else {

          // 切记将路由push到routes后还需要使用addRoute,这样路由才能正常跳转
          router.options.routes[0].children.push(v);
          // 最终路由进行升序
          ascending(router.options.routes[0].children);

          if (!router.hasRoute(v?.path)) router.addRoute(v);
          const flattenRouters: any = router
            .getRoutes()
            .find(n => n.path === "/");
          router.addRoute(flattenRouters);
        }
      }
    );
    usePermissionStoreHook().handleWholeMenus(newList);
  }
  addPathMatch();
}

初始化动态路由部分更改:

/** 初始化路由(`new Promise` 写法防止在异步请求中造成无限循环)*/
function initRouter() {
  if (getConfig()?.CachingAsyncRoutes) {
    console.log('一');

    // 开启动态路由缓存本地localStorage
    const key = "async-routes";
    const asyncRouteList = storageLocal().getItem(key) as any;
    if (asyncRouteList && asyncRouteList?.length > 0) {
      return new Promise(resolve => {
        handleAsyncRoutes(asyncRouteList);
        resolve(router);
      });
    } else {
      console.log('二');
      let aa = JSON.parse(sessionStorage.getItem('afterLogin'))
      return new Promise(resolve => {
        handleAsyncRoutes(cloneDeep(routerMenus(aa.list)));
        resolve(router);
      });
    }
  } else {
    console.log('三');
    let aa = JSON.parse(sessionStorage.getItem('afterLogin'))
    // return new Promise(resolve => {
    //   console.log('三');
    //   console.log(routerMenus(aa.list));
    //   handleAsyncRoutes(cloneDeep(routerMenus(aa.list)));
    //   // console.log();
    //   // usePermissionStoreHook().handleWholeMenus(routerMenus(cloneDeep(aa.list)));
    //   resolve(router);
    //   // getAsyncRoutes().then(({ data }) => {
    //   // console.log(data);
    //   // });
    // });
    return new Promise(resolve => {
      console.log('三');
      if (aa == null || aa == undefined || aa == '') {
        sessionStorage.setItem('afterLogin', null)
        console.log('跳转');
        useUserStoreHook().logOut();
      } else {
        console.log('通过');
        console.log(routerMenus(aa.list));
        handleAsyncRoutes(cloneDeep(routerMenus(aa.list)));
        // console.log();
        // usePermissionStoreHook().handleWholeMenus(routerMenus(cloneDeep(aa.list)));
        resolve(router);
        // getAsyncRoutes().then(({ data }) => {
        // console.log(data);
        // });
      }

    });
  }
}

后端扁平数据处理:

let bbbb = ''
function routerMenus(list) {
  let mneuobj = {}
  let arrobj = []

  for (let item of list) {
    if (item.children) {
      bbbb = item.path
      arrobj.push(mneuobj = {
        path: item.path,
        meta: {
          icon: item.icon,
          title: item.title,
          rank: item.sort
        },
        children: routerMenus(item.children)
      })
    } else {
      let stes = item.path.replace(/\//g, '')
      if (bbbb == '/') {
        arrobj.push(mneuobj = {
          path: `${item.path}`,
          name: stes.charAt(0).toUpperCase() + stes.slice(1),
          meta: {
            icon: item.icon,
            title: item.title
          }
        })
      } else {
        arrobj.push(mneuobj = {
          path: `${bbbb}${item.path}`,
          name: stes.charAt(0).toUpperCase() + stes.slice(1),
          meta: {
            icon: item.icon,
            title: item.title
          }
        })
      }

    }
  }
  sessionStorage.setItem('lastData', JSON.stringify(arrobj))
  return arrobj;
}

其他的地方更改不大,后续有时间会总结动态路由的更改思路? ( ????ω???)??3???

文章来源:https://blog.csdn.net/Z_B_L/article/details/135722540
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。