vue3 多级动态路由

vue 多级动态路由


import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import store from "@/store";
import { getToken } from "@/utils/auth";

const routes: Array<RouteRecordRaw> = [
  {
    path: "/login",
    name: "Login",
    component: () => import("@/views/login/index.vue"),
  },
  {
    path: "/layout",
    name: "layout",
    component: () => import("@/layout/index.vue"),
    children: [
      {
        path: "/403",
        name: "404",
        component: () => import("@/views/exception/403.vue"),
      },
      {
        path: "/404",
        name: "404",
        component: () => import("@/views/exception/404.vue"),
      },
      {
        path: "/500",
        name: "500",
        component: () => import("@/views/exception/500.vue"),
      },
      {
        path: "/home",
        name: "首页",
        component: () => import("@/views/home/index.vue"),
      },
    ],
  },
  {
    path: "/",
    name: "/",
    redirect: "/login",
  },
  {
    path: "/:pathMatch(.*)",
    redirect: "/404",
  },
];
const router = createRouter({
  history: createWebHashHistory(),
  routes,
});
var isF = false; //这个是用于判断动态路由是否已经被获取
router.beforeEach(async (to, from) => {
  if (to.path == "/login") {
    return true;
  }
  if (!getToken()) {
    return { path: "/login" };
  } else {
    if (isF) {
      return true;
    } else {
      let add = store.getters.menuList || "";
      routerData(add);
      isF = true;
      return { ...to, replace: true };
    }
  }
});
const routerData = (result: any) => {
  let currenRoutes = router.options.routes;
  if (result) {
    result.forEach((item: any) => {
      // has用于判断当前路由中是否已经具有,避免重复
      var has = currenRoutes.some((it) => it.path == item.path);
      if (!has) {
        currenRoutes.push({
          path: `${item.url}`,
          name: item.name,
          meta: {
            title: item.name,
          },
          component: () => import(`@/views${item.url}`),
        });
        router.addRoute("layout", {
          path: `${item.url}`,
          name: item.name,
          meta: {
            title: item.name,
          },
          component: () => import(`@/views${item.url}`),
        });
      }
      if (item.children && item.children.length) {
        routerData(item.children);
      }
    });
  }
};

export default router;

你可能感兴趣的:(vue,vue.js,前端,javascript)