12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- /**
- * 通过menus 计算出asyncRoutes 动态路由
- */
- import { RouteRecordRaw } from "vue-router"
- import { asyncComponentsType } from "@/router/routers"
- export const generateAsyncMenusAsyncRoutes = (menus: menuType[], components: asyncComponentsType) => {
- return {
- asyncRoutes: generateAsyncRoutes(menus, components),
- asyncMenus: generateAsyncMenus(menus)
- }
- }
- export const generateAsyncRoutes = (menus: menuType[], components: asyncComponentsType) => {
- function menusAsyncRoutes(menus: menuType[]) {
- const layoutRoutes: RouteRecordRaw[] = []
- const singlepageRoutes: RouteRecordRaw[] = []
- for (const menu of menus) {
- const { path, component, meta } = menu
- if (menu.children && menu.children.length > 0) {
- const asyncRoutes = menusAsyncRoutes(menu.children)
- layoutRoutes.push(...asyncRoutes.layoutRoutes)
- singlepageRoutes.push(...asyncRoutes.singlepageRoutes)
- } else {
- ;(meta.routeType === "layout" ? layoutRoutes : singlepageRoutes).push({
- path: path,
- name: component,
- component: components[component],
- meta
- })
- }
- }
- return {
- layoutRoutes,
- singlepageRoutes
- }
- }
- const { layoutRoutes, singlepageRoutes } = menusAsyncRoutes(menus)
- const asyncRoutes: RouteRecordRaw[] = [
- {
- path: "/layout",
- name: "layout",
- redirect: "/noRedirect",
- component: components["layout"],
- children: layoutRoutes
- },
- ...singlepageRoutes
- ]
- //默认获取第一个菜单为首页
- function getHomePageMenus(menus: menuType[]): string {
- const menu = menus[0]
- if (!menu) {
- return "/noRedirect"
- } else if (menu.children && menu.children.length) {
- return getHomePageMenus(menu.children)
- } else {
- return menu.path
- }
- }
- const homePagePath = getHomePageMenus(menus)
- //添加首页
- asyncRoutes.push({
- path: "/",
- redirect: homePagePath
- })
- //添加 404
- asyncRoutes.push({
- path: "/:pathMatch(.*)*",
- name: "errorPage",
- component: () => import("@/viewsframe/errorPage")
- })
- return asyncRoutes
- }
- export const generateAsyncMenus = (menus: menuType[]) => {
- return filterMenus(menus)
- function filterMenus(menus: menuType[]) {
- return menus.filter(item => {
- if (item.children.length) {
- item.children = filterMenus(item.children)
- }
- return item.meta.routeType === "layout"
- })
- }
- }
|