Vue3 + Vite + Vue Router 4后端返回路由配置动态路由权限管理

Vue3 + Vite + Vue Router 4后端返回路由配置动态路由权限管理

韩小韩
2023-07-28 / 0 评论 / 7,029 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2023年07月28日,已超过323天没有更新,若内容或图片失效,请留言反馈。

动态路由

// 路由递归处理
const AllRouter = import.meta.glob('@/views/**/*.vue');
interface RouterItem {
  path: string;
  name: string;
  component: () => any;
  children?: RouterItem[];
  meta: {
    title: string;
    icon: string;
  };
}
const routerFormat = (routerList: any): RouterItem[] => {
  if (!routerList || !Array.isArray(routerList)) return [];
  return routerList.map((item: any) => {
    return {
      ...item,
      component: AllRouter[`/src/views/${item['component']}`],
      children: routerFormat(item['children'])
    };
  });
};
// 动态路由挂载
const addDynamicRoutes = (layoutRoute: RouteRecordRaw | undefined, page: RouteLocationNormalizedLoaded) => {
  const newRouteStr = localStorage.getItem('routerList');
  if (layoutRoute && newRouteStr && layoutRoute.children!.length < 1) {
    const newRouteArr = routerFormat(JSON.parse(newRouteStr) as RouteRecordRaw[]);
    layoutRoute.children = newRouteArr;
    router.addRoute(layoutRoute);
    router.push(page);
  }
};

路由守卫

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 每次请求判断动态路由是否挂载
  const layoutRoute: RouteRecordRaw | undefined = router.options.routes.find(route=> route.name === 'Layout');
  addDynamicRoutes(layoutRoute, to);
  // 路由拦截规则
  const TOKEN_STATIC: string | null = localStorage.getItem('session');
  if (to.path === '/login' && TOKEN_STATIC) {
    next('/Layout');
  } else {
    !TOKEN_STATIC && to.path !== '/login' ? next('/login') : next();
  }
});

Login获取路由信息

// 路由递归处理
const routerFormat = (routerList: any[]): any[] => {
  if (!routerList) return [];
  return routerList.map((item: any) => {
    return {
      path: item['url'],
      name: item['title'],
      component: item['component'],
      children: routerFormat(item['children']),
      meta: {
        title: item['title'],
        icon: item['ico']
      }
    };
  });
};
// 获取用户信息
const getUserInfoFn = async (session: any) => {
  localStorage.setItem('session', session);
  const res = await getUserInfo();
  if (res.code == 0) {
    const routerList = routerFormat(res.data.router_list);
    localStorage.setItem('userInfo', JSON.stringify(res.data.user_info));
    localStorage.setItem('routerList', JSON.stringify(routerList));
    router.push({ name: 'Layout' });
  }
};
2

评论 (0)

取消