mirror of
https://github.com/fumiama/paper-manager.git
synced 2026-06-10 19:10:25 +08:00
add frontend/vben from vben-admin-thin
This commit is contained in:
24
frontend/vben/src/router/constant.ts
Normal file
24
frontend/vben/src/router/constant.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
export const REDIRECT_NAME = 'Redirect'
|
||||
|
||||
export const PARENT_LAYOUT_NAME = 'ParentLayout'
|
||||
|
||||
export const PAGE_NOT_FOUND_NAME = 'PageNotFound'
|
||||
|
||||
export const EXCEPTION_COMPONENT = () => import('/@/views/sys/exception/Exception.vue')
|
||||
|
||||
/**
|
||||
* @description: default layout
|
||||
*/
|
||||
export const LAYOUT = () => import('/@/layouts/default/index.vue')
|
||||
|
||||
/**
|
||||
* @description: parent-layout
|
||||
*/
|
||||
export const getParentLayout = (_name?: string) => {
|
||||
return () =>
|
||||
new Promise((resolve) => {
|
||||
resolve({
|
||||
name: PARENT_LAYOUT_NAME,
|
||||
})
|
||||
})
|
||||
}
|
||||
147
frontend/vben/src/router/guard/index.ts
Normal file
147
frontend/vben/src/router/guard/index.ts
Normal file
@@ -0,0 +1,147 @@
|
||||
import type { Router, RouteLocationNormalized } from 'vue-router'
|
||||
import { useAppStoreWithOut } from '/@/store/modules/app'
|
||||
import { useUserStoreWithOut } from '/@/store/modules/user'
|
||||
import { useTransitionSetting } from '/@/hooks/setting/useTransitionSetting'
|
||||
import { AxiosCanceler } from '/@/utils/http/axios/axiosCancel'
|
||||
import { Modal, notification } from 'ant-design-vue'
|
||||
import { warn } from '/@/utils/log'
|
||||
import { unref } from 'vue'
|
||||
import { setRouteChange } from '/@/logics/mitt/routeChange'
|
||||
import { createPermissionGuard } from './permissionGuard'
|
||||
import { createStateGuard } from './stateGuard'
|
||||
import nProgress from 'nprogress'
|
||||
import projectSetting from '/@/settings/projectSetting'
|
||||
import { createParamMenuGuard } from './paramMenuGuard'
|
||||
|
||||
// Don't change the order of creation
|
||||
export function setupRouterGuard(router: Router) {
|
||||
createPageGuard(router)
|
||||
createPageLoadingGuard(router)
|
||||
createHttpGuard(router)
|
||||
createScrollGuard(router)
|
||||
createMessageGuard(router)
|
||||
createProgressGuard(router)
|
||||
createPermissionGuard(router)
|
||||
createParamMenuGuard(router) // must after createPermissionGuard (menu has been built.)
|
||||
createStateGuard(router)
|
||||
}
|
||||
|
||||
/**
|
||||
* Hooks for handling page state
|
||||
*/
|
||||
function createPageGuard(router: Router) {
|
||||
const loadedPageMap = new Map<string, boolean>()
|
||||
|
||||
router.beforeEach(async (to) => {
|
||||
// The page has already been loaded, it will be faster to open it again, you don’t need to do loading and other processing
|
||||
to.meta.loaded = !!loadedPageMap.get(to.path)
|
||||
// Notify routing changes
|
||||
setRouteChange(to)
|
||||
|
||||
return true
|
||||
})
|
||||
|
||||
router.afterEach((to) => {
|
||||
loadedPageMap.set(to.path, true)
|
||||
})
|
||||
}
|
||||
|
||||
// Used to handle page loading status
|
||||
function createPageLoadingGuard(router: Router) {
|
||||
const userStore = useUserStoreWithOut()
|
||||
const appStore = useAppStoreWithOut()
|
||||
const { getOpenPageLoading } = useTransitionSetting()
|
||||
router.beforeEach(async (to) => {
|
||||
if (!userStore.getToken) {
|
||||
return true
|
||||
}
|
||||
if (to.meta.loaded) {
|
||||
return true
|
||||
}
|
||||
|
||||
if (unref(getOpenPageLoading)) {
|
||||
appStore.setPageLoadingAction(true)
|
||||
return true
|
||||
}
|
||||
|
||||
return true
|
||||
})
|
||||
router.afterEach(async () => {
|
||||
if (unref(getOpenPageLoading)) {
|
||||
// TODO Looking for a better way
|
||||
// The timer simulates the loading time to prevent flashing too fast,
|
||||
setTimeout(() => {
|
||||
appStore.setPageLoading(false)
|
||||
}, 220)
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* The interface used to close the current page to complete the request when the route is switched
|
||||
* @param router
|
||||
*/
|
||||
function createHttpGuard(router: Router) {
|
||||
const { removeAllHttpPending } = projectSetting
|
||||
let axiosCanceler: Nullable<AxiosCanceler>
|
||||
if (removeAllHttpPending) {
|
||||
axiosCanceler = new AxiosCanceler()
|
||||
}
|
||||
router.beforeEach(async () => {
|
||||
// Switching the route will delete the previous request
|
||||
axiosCanceler?.removeAllPending()
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
// Routing switch back to the top
|
||||
function createScrollGuard(router: Router) {
|
||||
const isHash = (href: string) => {
|
||||
return /^#/.test(href)
|
||||
}
|
||||
|
||||
const body = document.body
|
||||
|
||||
router.afterEach(async (to) => {
|
||||
// scroll top
|
||||
isHash((to as RouteLocationNormalized & { href: string })?.href) && body.scrollTo(0, 0)
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Used to close the message instance when the route is switched
|
||||
* @param router
|
||||
*/
|
||||
export function createMessageGuard(router: Router) {
|
||||
const { closeMessageOnSwitch } = projectSetting
|
||||
|
||||
router.beforeEach(async () => {
|
||||
try {
|
||||
if (closeMessageOnSwitch) {
|
||||
Modal.destroyAll()
|
||||
notification.destroy()
|
||||
}
|
||||
} catch (error) {
|
||||
warn('message guard error:' + error)
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
export function createProgressGuard(router: Router) {
|
||||
const { getOpenNProgress } = useTransitionSetting()
|
||||
router.beforeEach(async (to) => {
|
||||
if (to.meta.loaded) {
|
||||
return true
|
||||
}
|
||||
unref(getOpenNProgress) && nProgress.start()
|
||||
return true
|
||||
})
|
||||
|
||||
router.afterEach(async () => {
|
||||
unref(getOpenNProgress) && nProgress.done()
|
||||
return true
|
||||
})
|
||||
}
|
||||
47
frontend/vben/src/router/guard/paramMenuGuard.ts
Normal file
47
frontend/vben/src/router/guard/paramMenuGuard.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import type { Router } from 'vue-router'
|
||||
import { configureDynamicParamsMenu } from '../helper/menuHelper'
|
||||
import { Menu } from '../types'
|
||||
import { PermissionModeEnum } from '/@/enums/appEnum'
|
||||
import { useAppStoreWithOut } from '/@/store/modules/app'
|
||||
|
||||
import { usePermissionStoreWithOut } from '/@/store/modules/permission'
|
||||
|
||||
export function createParamMenuGuard(router: Router) {
|
||||
const permissionStore = usePermissionStoreWithOut()
|
||||
router.beforeEach(async (to, _, next) => {
|
||||
// filter no name route
|
||||
if (!to.name) {
|
||||
next()
|
||||
return
|
||||
}
|
||||
|
||||
// menu has been built.
|
||||
if (!permissionStore.getIsDynamicAddedRoute) {
|
||||
next()
|
||||
return
|
||||
}
|
||||
|
||||
let menus: Menu[] = []
|
||||
if (isBackMode()) {
|
||||
menus = permissionStore.getBackMenuList
|
||||
} else if (isRouteMappingMode()) {
|
||||
menus = permissionStore.getFrontMenuList
|
||||
}
|
||||
menus.forEach((item) => configureDynamicParamsMenu(item, to.params))
|
||||
|
||||
next()
|
||||
})
|
||||
}
|
||||
|
||||
const getPermissionMode = () => {
|
||||
const appStore = useAppStoreWithOut()
|
||||
return appStore.getProjectConfig.permissionMode
|
||||
}
|
||||
|
||||
const isBackMode = () => {
|
||||
return getPermissionMode() === PermissionModeEnum.BACK
|
||||
}
|
||||
|
||||
const isRouteMappingMode = () => {
|
||||
return getPermissionMode() === PermissionModeEnum.ROUTE_MAPPING
|
||||
}
|
||||
118
frontend/vben/src/router/guard/permissionGuard.ts
Normal file
118
frontend/vben/src/router/guard/permissionGuard.ts
Normal file
@@ -0,0 +1,118 @@
|
||||
import type { Router, RouteRecordRaw } from 'vue-router'
|
||||
|
||||
import { usePermissionStoreWithOut } from '/@/store/modules/permission'
|
||||
|
||||
import { PageEnum } from '/@/enums/pageEnum'
|
||||
import { useUserStoreWithOut } from '/@/store/modules/user'
|
||||
|
||||
import { PAGE_NOT_FOUND_ROUTE } from '/@/router/routes/basic'
|
||||
|
||||
import { RootRoute } from '/@/router/routes'
|
||||
|
||||
const LOGIN_PATH = PageEnum.BASE_LOGIN
|
||||
|
||||
const ROOT_PATH = RootRoute.path
|
||||
|
||||
const whitePathList: PageEnum[] = [LOGIN_PATH]
|
||||
|
||||
export function createPermissionGuard(router: Router) {
|
||||
const userStore = useUserStoreWithOut()
|
||||
const permissionStore = usePermissionStoreWithOut()
|
||||
router.beforeEach(async (to, from, next) => {
|
||||
if (
|
||||
from.path === ROOT_PATH &&
|
||||
to.path === PageEnum.BASE_HOME &&
|
||||
userStore.getUserInfo.homePath &&
|
||||
userStore.getUserInfo.homePath !== PageEnum.BASE_HOME
|
||||
) {
|
||||
next(userStore.getUserInfo.homePath)
|
||||
return
|
||||
}
|
||||
|
||||
const token = userStore.getToken
|
||||
|
||||
// Whitelist can be directly entered
|
||||
if (whitePathList.includes(to.path as PageEnum)) {
|
||||
if (to.path === LOGIN_PATH && token) {
|
||||
const isSessionTimeout = userStore.getSessionTimeout
|
||||
try {
|
||||
await userStore.afterLoginAction()
|
||||
if (!isSessionTimeout) {
|
||||
next((to.query?.redirect as string) || '/')
|
||||
return
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
next()
|
||||
return
|
||||
}
|
||||
|
||||
// token does not exist
|
||||
if (!token) {
|
||||
// You can access without permission. You need to set the routing meta.ignoreAuth to true
|
||||
if (to.meta.ignoreAuth) {
|
||||
next()
|
||||
return
|
||||
}
|
||||
|
||||
// redirect login page
|
||||
const redirectData: { path: string; replace: boolean; query?: Recordable<string> } = {
|
||||
path: LOGIN_PATH,
|
||||
replace: true,
|
||||
}
|
||||
if (to.path) {
|
||||
redirectData.query = {
|
||||
...redirectData.query,
|
||||
redirect: to.path,
|
||||
}
|
||||
}
|
||||
next(redirectData)
|
||||
return
|
||||
}
|
||||
|
||||
// Jump to the 404 page after processing the login
|
||||
if (
|
||||
from.path === LOGIN_PATH &&
|
||||
to.name === PAGE_NOT_FOUND_ROUTE.name &&
|
||||
to.fullPath !== (userStore.getUserInfo.homePath || PageEnum.BASE_HOME)
|
||||
) {
|
||||
next(userStore.getUserInfo.homePath || PageEnum.BASE_HOME)
|
||||
return
|
||||
}
|
||||
|
||||
// get userinfo while last fetch time is empty
|
||||
if (userStore.getLastUpdateTime === 0) {
|
||||
try {
|
||||
await userStore.getUserInfoAction()
|
||||
} catch (err) {
|
||||
next()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if (permissionStore.getIsDynamicAddedRoute) {
|
||||
next()
|
||||
return
|
||||
}
|
||||
|
||||
const routes = await permissionStore.buildRoutesAction()
|
||||
|
||||
routes.forEach((route) => {
|
||||
router.addRoute(route as unknown as RouteRecordRaw)
|
||||
})
|
||||
|
||||
router.addRoute(PAGE_NOT_FOUND_ROUTE as unknown as RouteRecordRaw)
|
||||
|
||||
permissionStore.setDynamicAddedRoute(true)
|
||||
|
||||
if (to.name === PAGE_NOT_FOUND_ROUTE.name) {
|
||||
// 动态添加路由后,此处应当重定向到fullPath,否则会加载404页面内容
|
||||
next({ path: to.fullPath, replace: true, query: to.query })
|
||||
} else {
|
||||
const redirectPath = (from.query.redirect || to.path) as string
|
||||
const redirect = decodeURIComponent(redirectPath)
|
||||
const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect }
|
||||
next(nextData)
|
||||
}
|
||||
})
|
||||
}
|
||||
24
frontend/vben/src/router/guard/stateGuard.ts
Normal file
24
frontend/vben/src/router/guard/stateGuard.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import type { Router } from 'vue-router'
|
||||
import { useAppStore } from '/@/store/modules/app'
|
||||
import { useMultipleTabStore } from '/@/store/modules/multipleTab'
|
||||
import { useUserStore } from '/@/store/modules/user'
|
||||
import { usePermissionStore } from '/@/store/modules/permission'
|
||||
import { PageEnum } from '/@/enums/pageEnum'
|
||||
import { removeTabChangeListener } from '/@/logics/mitt/routeChange'
|
||||
|
||||
export function createStateGuard(router: Router) {
|
||||
router.afterEach((to) => {
|
||||
// Just enter the login page and clear the authentication information
|
||||
if (to.path === PageEnum.BASE_LOGIN) {
|
||||
const tabStore = useMultipleTabStore()
|
||||
const userStore = useUserStore()
|
||||
const appStore = useAppStore()
|
||||
const permissionStore = usePermissionStore()
|
||||
appStore.resetAllState()
|
||||
permissionStore.resetState()
|
||||
tabStore.resetState()
|
||||
userStore.resetState()
|
||||
removeTabChangeListener()
|
||||
}
|
||||
})
|
||||
}
|
||||
106
frontend/vben/src/router/helper/menuHelper.ts
Normal file
106
frontend/vben/src/router/helper/menuHelper.ts
Normal file
@@ -0,0 +1,106 @@
|
||||
import { AppRouteModule } from '/@/router/types'
|
||||
import type { MenuModule, Menu, AppRouteRecordRaw } from '/@/router/types'
|
||||
import { findPath, treeMap } from '/@/utils/helper/treeHelper'
|
||||
import { cloneDeep } from 'lodash-es'
|
||||
import { isUrl } from '/@/utils/is'
|
||||
import { RouteParams } from 'vue-router'
|
||||
import { toRaw } from 'vue'
|
||||
|
||||
export function getAllParentPath<T = Recordable>(treeData: T[], path: string) {
|
||||
const menuList = findPath(treeData, (n) => n.path === path) as Menu[]
|
||||
return (menuList || []).map((item) => item.path)
|
||||
}
|
||||
|
||||
// 路径处理
|
||||
function joinParentPath(menus: Menu[], parentPath = '') {
|
||||
for (let index = 0; index < menus.length; index++) {
|
||||
const menu = menus[index]
|
||||
// https://next.router.vuejs.org/guide/essentials/nested-routes.html
|
||||
// Note that nested paths that start with / will be treated as a root path.
|
||||
// 请注意,以 / 开头的嵌套路径将被视为根路径。
|
||||
// This allows you to leverage the component nesting without having to use a nested URL.
|
||||
// 这允许你利用组件嵌套,而无需使用嵌套 URL。
|
||||
if (!(menu.path.startsWith('/') || isUrl(menu.path))) {
|
||||
// path doesn't start with /, nor is it a url, join parent path
|
||||
// 路径不以 / 开头,也不是 url,加入父路径
|
||||
menu.path = `${parentPath}/${menu.path}`
|
||||
}
|
||||
if (menu?.children?.length) {
|
||||
joinParentPath(menu.children, menu.meta?.hidePathForChildren ? parentPath : menu.path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Parsing the menu module
|
||||
export function transformMenuModule(menuModule: MenuModule): Menu {
|
||||
const { menu } = menuModule
|
||||
|
||||
const menuList = [menu]
|
||||
|
||||
joinParentPath(menuList)
|
||||
return menuList[0]
|
||||
}
|
||||
|
||||
// 将路由转换成菜单
|
||||
export function transformRouteToMenu(routeModList: AppRouteModule[], routerMapping = false) {
|
||||
// 借助 lodash 深拷贝
|
||||
const cloneRouteModList = cloneDeep(routeModList)
|
||||
const routeList: AppRouteRecordRaw[] = []
|
||||
|
||||
// 对路由项进行修改
|
||||
cloneRouteModList.forEach((item) => {
|
||||
if (routerMapping && item.meta.hideChildrenInMenu && typeof item.redirect === 'string') {
|
||||
item.path = item.redirect
|
||||
}
|
||||
|
||||
if (item.meta?.single) {
|
||||
const realItem = item?.children?.[0]
|
||||
realItem && routeList.push(realItem)
|
||||
} else {
|
||||
routeList.push(item)
|
||||
}
|
||||
})
|
||||
// 提取树指定结构
|
||||
const list = treeMap(routeList, {
|
||||
conversion: (node: AppRouteRecordRaw) => {
|
||||
const { meta: { title, hideMenu = false } = {} } = node
|
||||
|
||||
return {
|
||||
...(node.meta || {}),
|
||||
meta: node.meta,
|
||||
name: title,
|
||||
hideMenu,
|
||||
path: node.path,
|
||||
...(node.redirect ? { redirect: node.redirect } : {}),
|
||||
}
|
||||
},
|
||||
})
|
||||
// 路径处理
|
||||
joinParentPath(list)
|
||||
return cloneDeep(list)
|
||||
}
|
||||
|
||||
/**
|
||||
* config menu with given params
|
||||
*/
|
||||
const menuParamRegex = /(?::)([\s\S]+?)((?=\/)|$)/g
|
||||
|
||||
export function configureDynamicParamsMenu(menu: Menu, params: RouteParams) {
|
||||
const { path, paramPath } = toRaw(menu)
|
||||
let realPath = paramPath ? paramPath : path
|
||||
const matchArr = realPath.match(menuParamRegex)
|
||||
|
||||
matchArr?.forEach((it) => {
|
||||
const realIt = it.substr(1)
|
||||
if (params[realIt]) {
|
||||
realPath = realPath.replace(`:${realIt}`, params[realIt] as string)
|
||||
}
|
||||
})
|
||||
// save original param path.
|
||||
if (!paramPath && matchArr && matchArr.length > 0) {
|
||||
menu.paramPath = path
|
||||
}
|
||||
menu.path = realPath
|
||||
// children
|
||||
menu.children?.forEach((item) => configureDynamicParamsMenu(item, params))
|
||||
}
|
||||
172
frontend/vben/src/router/helper/routeHelper.ts
Normal file
172
frontend/vben/src/router/helper/routeHelper.ts
Normal file
@@ -0,0 +1,172 @@
|
||||
import type { AppRouteModule, AppRouteRecordRaw } from '/@/router/types'
|
||||
import type { Router, RouteRecordNormalized } from 'vue-router'
|
||||
|
||||
import { getParentLayout, LAYOUT, EXCEPTION_COMPONENT } from '/@/router/constant'
|
||||
import { cloneDeep, omit } from 'lodash-es'
|
||||
import { warn } from '/@/utils/log'
|
||||
import { createRouter, createWebHashHistory } from 'vue-router'
|
||||
|
||||
export type LayoutMapKey = 'LAYOUT'
|
||||
const LayoutMap = new Map<string, () => Promise<typeof import('*.vue')>>()
|
||||
|
||||
LayoutMap.set('LAYOUT', LAYOUT)
|
||||
|
||||
let dynamicViewsModules: Record<string, () => Promise<Recordable>>
|
||||
|
||||
// Dynamic introduction
|
||||
function asyncImportRoute(routes: AppRouteRecordRaw[] | undefined) {
|
||||
dynamicViewsModules = dynamicViewsModules || import.meta.glob('../../views/**/*.{vue,tsx}')
|
||||
if (!routes) return
|
||||
routes.forEach((item) => {
|
||||
const { component, name } = item
|
||||
const { children } = item
|
||||
if (component) {
|
||||
const layoutFound = LayoutMap.get(component.toUpperCase())
|
||||
if (layoutFound) {
|
||||
item.component = layoutFound
|
||||
} else {
|
||||
item.component = dynamicImport(dynamicViewsModules, component as string)
|
||||
}
|
||||
} else if (name) {
|
||||
item.component = getParentLayout()
|
||||
}
|
||||
children && asyncImportRoute(children)
|
||||
})
|
||||
}
|
||||
|
||||
function dynamicImport(
|
||||
dynamicViewsModules: Record<string, () => Promise<Recordable>>,
|
||||
component: string,
|
||||
) {
|
||||
const keys = Object.keys(dynamicViewsModules)
|
||||
const matchKeys = keys.filter((key) => {
|
||||
const k = key.replace('../../views', '')
|
||||
const startFlag = component.startsWith('/')
|
||||
const endFlag = component.endsWith('.vue') || component.endsWith('.tsx')
|
||||
const startIndex = startFlag ? 0 : 1
|
||||
const lastIndex = endFlag ? k.length : k.lastIndexOf('.')
|
||||
return k.substring(startIndex, lastIndex) === component
|
||||
})
|
||||
if (matchKeys?.length === 1) {
|
||||
const matchKey = matchKeys[0]
|
||||
return dynamicViewsModules[matchKey]
|
||||
} else if (matchKeys?.length > 1) {
|
||||
warn(
|
||||
'Please do not create `.vue` and `.TSX` files with the same file name in the same hierarchical directory under the views folder. This will cause dynamic introduction failure',
|
||||
)
|
||||
return
|
||||
} else {
|
||||
warn('在src/views/下找不到`' + component + '.vue` 或 `' + component + '.tsx`, 请自行创建!')
|
||||
return EXCEPTION_COMPONENT
|
||||
}
|
||||
}
|
||||
|
||||
// Turn background objects into routing objects
|
||||
// 将背景对象变成路由对象
|
||||
export function transformObjToRoute<T = AppRouteModule>(routeList: AppRouteModule[]): T[] {
|
||||
routeList.forEach((route) => {
|
||||
const component = route.component as string
|
||||
if (component) {
|
||||
if (component.toUpperCase() === 'LAYOUT') {
|
||||
route.component = LayoutMap.get(component.toUpperCase())
|
||||
} else {
|
||||
route.children = [cloneDeep(route)]
|
||||
route.component = LAYOUT
|
||||
route.name = `${route.name}Parent`
|
||||
route.path = ''
|
||||
const meta = route.meta || {}
|
||||
meta.single = true
|
||||
meta.affix = false
|
||||
route.meta = meta
|
||||
}
|
||||
} else {
|
||||
warn('请正确配置路由:' + route?.name + '的component属性')
|
||||
}
|
||||
route.children && asyncImportRoute(route.children)
|
||||
})
|
||||
return routeList as unknown as T[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert multi-level routing to level 2 routing
|
||||
* 将多级路由转换为 2 级路由
|
||||
*/
|
||||
export function flatMultiLevelRoutes(routeModules: AppRouteModule[]) {
|
||||
const modules: AppRouteModule[] = cloneDeep(routeModules)
|
||||
|
||||
for (let index = 0; index < modules.length; index++) {
|
||||
const routeModule = modules[index]
|
||||
// 判断级别是否 多级 路由
|
||||
if (!isMultipleRoute(routeModule)) {
|
||||
// 声明终止当前循环, 即跳过此次循环,进行下一轮
|
||||
continue
|
||||
}
|
||||
// 路由等级提升
|
||||
promoteRouteLevel(routeModule)
|
||||
}
|
||||
return modules
|
||||
}
|
||||
|
||||
// Routing level upgrade
|
||||
// 路由等级提升
|
||||
function promoteRouteLevel(routeModule: AppRouteModule) {
|
||||
// Use vue-router to splice menus
|
||||
// 使用vue-router拼接菜单
|
||||
// createRouter 创建一个可以被 Vue 应用程序使用的路由实例
|
||||
let router: Router | null = createRouter({
|
||||
routes: [routeModule as unknown as RouteRecordNormalized],
|
||||
history: createWebHashHistory(),
|
||||
})
|
||||
// getRoutes: 获取所有 路由记录的完整列表。
|
||||
const routes = router.getRoutes()
|
||||
// 将所有子路由添加到二级路由
|
||||
addToChildren(routes, routeModule.children || [], routeModule)
|
||||
router = null
|
||||
|
||||
// omit lodash的函数 对传入的item对象的children进行删除
|
||||
routeModule.children = routeModule.children?.map((item) => omit(item, 'children'))
|
||||
}
|
||||
|
||||
// Add all sub-routes to the secondary route
|
||||
// 将所有子路由添加到二级路由
|
||||
function addToChildren(
|
||||
routes: RouteRecordNormalized[],
|
||||
children: AppRouteRecordRaw[],
|
||||
routeModule: AppRouteModule,
|
||||
) {
|
||||
for (let index = 0; index < children.length; index++) {
|
||||
const child = children[index]
|
||||
const route = routes.find((item) => item.name === child.name)
|
||||
if (!route) {
|
||||
continue
|
||||
}
|
||||
routeModule.children = routeModule.children || []
|
||||
if (!routeModule.children.find((item) => item.name === route.name)) {
|
||||
routeModule.children?.push(route as unknown as AppRouteModule)
|
||||
}
|
||||
if (child.children?.length) {
|
||||
addToChildren(routes, child.children, routeModule)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Determine whether the level exceeds 2 levels
|
||||
// 判断级别是否超过2级
|
||||
function isMultipleRoute(routeModule: AppRouteModule) {
|
||||
// Reflect.has 与 in 操作符 相同, 用于检查一个对象(包括它原型链上)是否拥有某个属性
|
||||
if (!routeModule || !Reflect.has(routeModule, 'children') || !routeModule.children?.length) {
|
||||
return false
|
||||
}
|
||||
|
||||
const children = routeModule.children
|
||||
|
||||
let flag = false
|
||||
for (let index = 0; index < children.length; index++) {
|
||||
const child = children[index]
|
||||
if (child.children?.length) {
|
||||
flag = true
|
||||
break
|
||||
}
|
||||
}
|
||||
return flag
|
||||
}
|
||||
42
frontend/vben/src/router/index.ts
Normal file
42
frontend/vben/src/router/index.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import type { RouteRecordRaw } from 'vue-router'
|
||||
import type { App } from 'vue'
|
||||
|
||||
import { createRouter, createWebHashHistory } from 'vue-router'
|
||||
import { basicRoutes } from './routes'
|
||||
|
||||
// 白名单应该包含基本静态路由
|
||||
const WHITE_NAME_LIST: string[] = []
|
||||
const getRouteNames = (array: any[]) =>
|
||||
array.forEach((item) => {
|
||||
WHITE_NAME_LIST.push(item.name)
|
||||
getRouteNames(item.children || [])
|
||||
})
|
||||
getRouteNames(basicRoutes)
|
||||
|
||||
// app router
|
||||
// 创建一个可以被 Vue 应用程序使用的路由实例
|
||||
export const router = createRouter({
|
||||
// 创建一个 hash 历史记录。
|
||||
history: createWebHashHistory(import.meta.env.VITE_PUBLIC_PATH),
|
||||
// 应该添加到路由的初始路由列表。
|
||||
routes: basicRoutes as unknown as RouteRecordRaw[],
|
||||
// 是否应该禁止尾部斜杠。默认为假
|
||||
strict: true,
|
||||
scrollBehavior: () => ({ left: 0, top: 0 }),
|
||||
})
|
||||
|
||||
// reset router
|
||||
export function resetRouter() {
|
||||
router.getRoutes().forEach((route) => {
|
||||
const { name } = route
|
||||
if (name && !WHITE_NAME_LIST.includes(name as string)) {
|
||||
router.hasRoute(name) && router.removeRoute(name)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// config router
|
||||
// 配置路由器
|
||||
export function setupRouter(app: App<Element>) {
|
||||
app.use(router)
|
||||
}
|
||||
126
frontend/vben/src/router/menus/index.ts
Normal file
126
frontend/vben/src/router/menus/index.ts
Normal file
@@ -0,0 +1,126 @@
|
||||
import type { Menu, MenuModule } from '/@/router/types'
|
||||
import type { RouteRecordNormalized } from 'vue-router'
|
||||
|
||||
import { useAppStoreWithOut } from '/@/store/modules/app'
|
||||
import { usePermissionStore } from '/@/store/modules/permission'
|
||||
import { transformMenuModule, getAllParentPath } from '/@/router/helper/menuHelper'
|
||||
import { filter } from '/@/utils/helper/treeHelper'
|
||||
import { isUrl } from '/@/utils/is'
|
||||
import { router } from '/@/router'
|
||||
import { PermissionModeEnum } from '/@/enums/appEnum'
|
||||
import { pathToRegexp } from 'path-to-regexp'
|
||||
|
||||
const modules = import.meta.globEager('./modules/**/*.ts')
|
||||
|
||||
const menuModules: MenuModule[] = []
|
||||
|
||||
Object.keys(modules).forEach((key) => {
|
||||
const mod = modules[key].default || {}
|
||||
const modList = Array.isArray(mod) ? [...mod] : [mod]
|
||||
menuModules.push(...modList)
|
||||
})
|
||||
|
||||
// ===========================
|
||||
// ==========Helper===========
|
||||
// ===========================
|
||||
|
||||
const getPermissionMode = () => {
|
||||
const appStore = useAppStoreWithOut()
|
||||
return appStore.getProjectConfig.permissionMode
|
||||
}
|
||||
const isBackMode = () => {
|
||||
return getPermissionMode() === PermissionModeEnum.BACK
|
||||
}
|
||||
|
||||
const isRouteMappingMode = () => {
|
||||
return getPermissionMode() === PermissionModeEnum.ROUTE_MAPPING
|
||||
}
|
||||
|
||||
const isRoleMode = () => {
|
||||
return getPermissionMode() === PermissionModeEnum.ROLE
|
||||
}
|
||||
|
||||
const staticMenus: Menu[] = []
|
||||
;(() => {
|
||||
menuModules.sort((a, b) => {
|
||||
return (a.orderNo || 0) - (b.orderNo || 0)
|
||||
})
|
||||
|
||||
for (const menu of menuModules) {
|
||||
staticMenus.push(transformMenuModule(menu))
|
||||
}
|
||||
})()
|
||||
|
||||
async function getAsyncMenus() {
|
||||
const permissionStore = usePermissionStore()
|
||||
if (isBackMode()) {
|
||||
return permissionStore.getBackMenuList.filter((item) => !item.meta?.hideMenu && !item.hideMenu)
|
||||
}
|
||||
if (isRouteMappingMode()) {
|
||||
return permissionStore.getFrontMenuList.filter((item) => !item.hideMenu)
|
||||
}
|
||||
return staticMenus
|
||||
}
|
||||
|
||||
export const getMenus = async (): Promise<Menu[]> => {
|
||||
const menus = await getAsyncMenus()
|
||||
if (isRoleMode()) {
|
||||
const routes = router.getRoutes()
|
||||
return filter(menus, basicFilter(routes))
|
||||
}
|
||||
return menus
|
||||
}
|
||||
|
||||
export async function getCurrentParentPath(currentPath: string) {
|
||||
const menus = await getAsyncMenus()
|
||||
const allParentPath = await getAllParentPath(menus, currentPath)
|
||||
return allParentPath?.[0]
|
||||
}
|
||||
|
||||
// Get the level 1 menu, delete children
|
||||
export async function getShallowMenus(): Promise<Menu[]> {
|
||||
const menus = await getAsyncMenus()
|
||||
const shallowMenuList = menus.map((item) => ({ ...item, children: undefined }))
|
||||
if (isRoleMode()) {
|
||||
const routes = router.getRoutes()
|
||||
return shallowMenuList.filter(basicFilter(routes))
|
||||
}
|
||||
return shallowMenuList
|
||||
}
|
||||
|
||||
// Get the children of the menu
|
||||
export async function getChildrenMenus(parentPath: string) {
|
||||
const menus = await getMenus()
|
||||
const parent = menus.find((item) => item.path === parentPath)
|
||||
if (!parent || !parent.children || !!parent?.meta?.hideChildrenInMenu) {
|
||||
return [] as Menu[]
|
||||
}
|
||||
if (isRoleMode()) {
|
||||
const routes = router.getRoutes()
|
||||
return filter(parent.children, basicFilter(routes))
|
||||
}
|
||||
return parent.children
|
||||
}
|
||||
|
||||
function basicFilter(routes: RouteRecordNormalized[]) {
|
||||
return (menu: Menu) => {
|
||||
const matchRoute = routes.find((route) => {
|
||||
if (isUrl(menu.path)) return true
|
||||
|
||||
if (route.meta?.carryParam) {
|
||||
return pathToRegexp(route.path).test(menu.path)
|
||||
}
|
||||
const isSame = route.path === menu.path
|
||||
if (!isSame) return false
|
||||
|
||||
if (route.meta?.ignoreAuth) return true
|
||||
|
||||
return isSame || pathToRegexp(route.path).test(menu.path)
|
||||
})
|
||||
|
||||
if (!matchRoute) return false
|
||||
menu.icon = (menu.icon || matchRoute.meta.icon) as string
|
||||
menu.meta = matchRoute.meta
|
||||
return true
|
||||
}
|
||||
}
|
||||
48
frontend/vben/src/router/routes/basic.ts
Normal file
48
frontend/vben/src/router/routes/basic.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import type { AppRouteRecordRaw } from '/@/router/types'
|
||||
import { REDIRECT_NAME, LAYOUT, EXCEPTION_COMPONENT, PAGE_NOT_FOUND_NAME } from '/@/router/constant'
|
||||
|
||||
// 404 on a page
|
||||
export const PAGE_NOT_FOUND_ROUTE: AppRouteRecordRaw = {
|
||||
path: '/:path(.*)*',
|
||||
name: PAGE_NOT_FOUND_NAME,
|
||||
component: LAYOUT,
|
||||
meta: {
|
||||
title: 'ErrorPage',
|
||||
hideBreadcrumb: true,
|
||||
hideMenu: true,
|
||||
},
|
||||
children: [
|
||||
{
|
||||
path: '/:path(.*)*',
|
||||
name: PAGE_NOT_FOUND_NAME,
|
||||
component: EXCEPTION_COMPONENT,
|
||||
meta: {
|
||||
title: 'ErrorPage',
|
||||
hideBreadcrumb: true,
|
||||
hideMenu: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
export const REDIRECT_ROUTE: AppRouteRecordRaw = {
|
||||
path: '/redirect',
|
||||
component: LAYOUT,
|
||||
name: 'RedirectTo',
|
||||
meta: {
|
||||
title: REDIRECT_NAME,
|
||||
hideBreadcrumb: true,
|
||||
hideMenu: true,
|
||||
},
|
||||
children: [
|
||||
{
|
||||
path: '/redirect/:path(.*)',
|
||||
name: REDIRECT_NAME,
|
||||
component: () => import('/@/views/sys/redirect/index.vue'),
|
||||
meta: {
|
||||
title: REDIRECT_NAME,
|
||||
hideBreadcrumb: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
42
frontend/vben/src/router/routes/index.ts
Normal file
42
frontend/vben/src/router/routes/index.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import type { AppRouteRecordRaw, AppRouteModule } from '/@/router/types'
|
||||
|
||||
import { PAGE_NOT_FOUND_ROUTE, REDIRECT_ROUTE } from '/@/router/routes/basic'
|
||||
|
||||
import { PageEnum } from '/@/enums/pageEnum'
|
||||
import { t } from '/@/hooks/web/useI18n'
|
||||
|
||||
// import.meta.globEager() 直接引入所有的模块 Vite 独有的功能
|
||||
const modules = import.meta.globEager('./modules/**/*.ts')
|
||||
const routeModuleList: AppRouteModule[] = []
|
||||
|
||||
// 加入到路由集合中
|
||||
Object.keys(modules).forEach((key) => {
|
||||
const mod = modules[key].default || {}
|
||||
const modList = Array.isArray(mod) ? [...mod] : [mod]
|
||||
routeModuleList.push(...modList)
|
||||
})
|
||||
|
||||
export const asyncRoutes = [PAGE_NOT_FOUND_ROUTE, ...routeModuleList]
|
||||
|
||||
// 根路由
|
||||
export const RootRoute: AppRouteRecordRaw = {
|
||||
path: '/',
|
||||
name: 'Root',
|
||||
redirect: PageEnum.BASE_HOME,
|
||||
meta: {
|
||||
title: 'Root',
|
||||
},
|
||||
}
|
||||
|
||||
export const LoginRoute: AppRouteRecordRaw = {
|
||||
path: '/login',
|
||||
name: 'Login',
|
||||
component: () => import('/@/views/sys/login/Login.vue'),
|
||||
meta: {
|
||||
title: t('routes.basic.login'),
|
||||
},
|
||||
}
|
||||
|
||||
// Basic routing without permission
|
||||
// 未经许可的基本路由
|
||||
export const basicRoutes = [LoginRoute, RootRoute, REDIRECT_ROUTE, PAGE_NOT_FOUND_ROUTE]
|
||||
31
frontend/vben/src/router/routes/modules/about.ts
Normal file
31
frontend/vben/src/router/routes/modules/about.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import type { AppRouteModule } from '/@/router/types'
|
||||
|
||||
import { LAYOUT } from '/@/router/constant'
|
||||
import { t } from '/@/hooks/web/useI18n'
|
||||
|
||||
const about: AppRouteModule = {
|
||||
path: '/about',
|
||||
name: 'About',
|
||||
component: LAYOUT,
|
||||
redirect: '/about/index',
|
||||
meta: {
|
||||
hideChildrenInMenu: true,
|
||||
icon: 'simple-icons:about-dot-me',
|
||||
title: t('routes.dashboard.about'),
|
||||
orderNo: 100000,
|
||||
},
|
||||
children: [
|
||||
{
|
||||
path: 'index',
|
||||
name: 'AboutPage',
|
||||
component: () => import('/@/views/sys/about/index.vue'),
|
||||
meta: {
|
||||
title: t('routes.dashboard.about'),
|
||||
icon: 'simple-icons:about-dot-me',
|
||||
hideMenu: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
export default about
|
||||
37
frontend/vben/src/router/routes/modules/dashboard.ts
Normal file
37
frontend/vben/src/router/routes/modules/dashboard.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import type { AppRouteModule } from '/@/router/types'
|
||||
|
||||
import { LAYOUT } from '/@/router/constant'
|
||||
import { t } from '/@/hooks/web/useI18n'
|
||||
|
||||
const dashboard: AppRouteModule = {
|
||||
path: '/dashboard',
|
||||
name: 'Dashboard',
|
||||
component: LAYOUT,
|
||||
redirect: '/dashboard/analysis',
|
||||
meta: {
|
||||
orderNo: 10,
|
||||
icon: 'ion:grid-outline',
|
||||
title: t('routes.dashboard.dashboard'),
|
||||
},
|
||||
children: [
|
||||
{
|
||||
path: 'analysis',
|
||||
name: 'Analysis',
|
||||
component: () => import('/@/views/dashboard/analysis/index.vue'),
|
||||
meta: {
|
||||
// affix: true,
|
||||
title: t('routes.dashboard.analysis'),
|
||||
},
|
||||
},
|
||||
{
|
||||
path: 'workbench',
|
||||
name: 'Workbench',
|
||||
component: () => import('/@/views/dashboard/workbench/index.vue'),
|
||||
meta: {
|
||||
title: t('routes.dashboard.workbench'),
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
export default dashboard
|
||||
31
frontend/vben/src/router/routes/modules/setup.ts
Normal file
31
frontend/vben/src/router/routes/modules/setup.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import type { AppRouteModule } from '/@/router/types'
|
||||
|
||||
import { LAYOUT } from '/@/router/constant'
|
||||
import { t } from '/@/hooks/web/useI18n'
|
||||
|
||||
const setup: AppRouteModule = {
|
||||
path: '/setup',
|
||||
name: 'SetupDemo',
|
||||
component: LAYOUT,
|
||||
redirect: '/setup/index',
|
||||
meta: {
|
||||
orderNo: 90000,
|
||||
hideChildrenInMenu: true,
|
||||
icon: 'whh:paintroll',
|
||||
title: t('routes.demo.setup.page'),
|
||||
},
|
||||
children: [
|
||||
{
|
||||
path: 'index',
|
||||
name: 'SetupDemoPage',
|
||||
component: () => import('/@/views/setup/index.vue'),
|
||||
meta: {
|
||||
title: t('routes.demo.setup.page'),
|
||||
icon: 'whh:paintroll',
|
||||
hideMenu: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
export default setup
|
||||
58
frontend/vben/src/router/types.ts
Normal file
58
frontend/vben/src/router/types.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
import type { RouteRecordRaw, RouteMeta } from 'vue-router'
|
||||
import { RoleEnum } from '/@/enums/roleEnum'
|
||||
import { defineComponent } from 'vue'
|
||||
|
||||
export type Component<T = any> =
|
||||
| ReturnType<typeof defineComponent>
|
||||
| (() => Promise<typeof import('*.vue')>)
|
||||
| (() => Promise<T>)
|
||||
|
||||
// @ts-ignore
|
||||
export interface AppRouteRecordRaw extends Omit<RouteRecordRaw, 'meta'> {
|
||||
name: string
|
||||
meta: RouteMeta
|
||||
component?: Component | string
|
||||
components?: Component
|
||||
children?: AppRouteRecordRaw[]
|
||||
props?: Recordable
|
||||
fullPath?: string
|
||||
}
|
||||
|
||||
export interface MenuTag {
|
||||
type?: 'primary' | 'error' | 'warn' | 'success'
|
||||
content?: string
|
||||
dot?: boolean
|
||||
}
|
||||
|
||||
export interface Menu {
|
||||
name: string
|
||||
|
||||
icon?: string
|
||||
|
||||
path: string
|
||||
|
||||
// path contains param, auto assignment.
|
||||
paramPath?: string
|
||||
|
||||
disabled?: boolean
|
||||
|
||||
children?: Menu[]
|
||||
|
||||
orderNo?: number
|
||||
|
||||
roles?: RoleEnum[]
|
||||
|
||||
meta?: Partial<RouteMeta>
|
||||
|
||||
tag?: MenuTag
|
||||
|
||||
hideMenu?: boolean
|
||||
}
|
||||
|
||||
export interface MenuModule {
|
||||
orderNo?: number
|
||||
menu: Menu
|
||||
}
|
||||
|
||||
// export type AppRouteModule = RouteModule | AppRouteRecordRaw;
|
||||
export type AppRouteModule = AppRouteRecordRaw
|
||||
Reference in New Issue
Block a user