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

2023-07-31 13:07:52 浏览数 (1)

动态路由

代码语言:javascript复制
// 动态路由
import type { RouteRecordRaw } from 'vue-router';
const AllRouter = import.meta.glob('@/views/**/*.vue');
const addDynamicRoutes = (layoutRoute: RouteRecordRaw, page: string) => {
  const newRouteStr = localStorage.getItem('routerList');
  if (layoutRoute && newRouteStr && layoutRoute.children.length < 1) {
    const newRouteArr = JSON.parse(newRouteStr) as RouteRecordRaw[];
    const layoutRouteName = layoutRoute.children.map((item) => item.name);
    Array.isArray(newRouteArr) &&
      newRouteArr.forEach((newRouteItem) => {
        const { path, name, meta, component } = newRouteItem;
        if (!layoutRouteName.includes(name)) {
          layoutRoute.children.push({
            path,
            name,
            meta,
            component: AllRouter[`/src/views/${component}`]
            // component: () => import(/* @vite-ignore */ `@/views/${component}`)
          });
        }
      });
    router.addRoute(layoutRoute);
    router.push(page);
  }
};

路由守卫

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

Login获取路由信息

代码语言:javascript复制
// 获取用户信息
const getUserInfoFn = async (session: string) => {
  localStorage.setItem('session', session);
  const res = await getUserInfo();
  if (res.code == 0) {
    localStorage.setItem('userInfo', JSON.stringify(res.data.user_info));
    localStorage.setItem('routerList',JSON.stringify(res.data.router_list));
    router.push({ name: 'Dashboard' });
  }
};

如有不妥,还请指点!

0 人点赞