UnisKB/ui/src/router/index.ts

91 lines
2.5 KiB
TypeScript
Raw Normal View History

2025-06-24 09:00:50 +00:00
import { hasPermission, set_next_route } from '@/utils/permission/index'
2025-04-25 08:27:13 +00:00
import NProgress from 'nprogress'
import {
createRouter,
createWebHistory,
type NavigationGuardNext,
type RouteLocationNormalized,
type RouteRecordRaw,
type RouteRecordName,
} from 'vue-router'
import useStore from '@/stores'
2025-04-16 11:10:00 +00:00
import { routes } from '@/router/routes'
2025-04-25 08:27:13 +00:00
NProgress.configure({ showSpinner: false, speed: 500, minimum: 0.3 })
2025-04-14 12:11:23 +00:00
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
2025-04-16 11:10:00 +00:00
routes: routes,
2025-04-14 12:11:23 +00:00
})
2025-04-25 08:27:13 +00:00
// 路由前置拦截器
router.beforeEach(
async (to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
NProgress.start()
if (to.name === '404') {
next()
return
}
const { user, login } = useStore()
2025-06-12 04:03:43 +00:00
const notAuthRouteNameList = ['login', 'ForgotPassword', 'ResetPassword', 'Chat', 'UserLogin']
2025-04-25 08:27:13 +00:00
if (!notAuthRouteNameList.includes(to.name ? to.name.toString() : '')) {
if (to.query && to.query.token) {
localStorage.setItem('token', to.query.token.toString())
}
const token = login.getToken()
if (!token) {
next({
path: '/login',
})
return
}
if (!user.userInfo) {
await user.profile()
}
}
2025-06-24 09:00:50 +00:00
set_next_route(to)
2025-04-25 08:27:13 +00:00
// 判断是否有菜单权限
if (to.meta.permission ? hasPermission(to.meta.permission as any, 'OR') : true) {
next()
} else {
2025-06-24 13:46:02 +00:00
console.log('s')
if (to.meta.get_permission_route) {
const t = to.meta.get_permission_route()
console.log(t)
next(t)
return
}
2025-04-25 08:27:13 +00:00
// 如果没有权限则直接取404页面
2025-06-24 13:16:43 +00:00
next({ path: '/no-permission' })
2025-04-25 08:27:13 +00:00
}
},
)
router.afterEach(() => {
NProgress.done()
})
export const getChildRouteListByPathAndName = (path: any, name?: RouteRecordName | any) => {
return getChildRouteList(routes, path, name)
}
export const getChildRouteList: (
routeList: Array<RouteRecordRaw>,
path: string,
name?: RouteRecordName | null | undefined,
) => Array<RouteRecordRaw> = (routeList, path, name) => {
for (let index = 0; index < routeList.length; index++) {
const route = routeList[index]
if (name === route.name && path === route.path) {
return route.children || []
}
if (route.children && route.children.length > 0) {
const result = getChildRouteList(route.children, path, name)
if (result && result?.length > 0) {
return result
}
}
}
return []
}
2025-04-14 12:11:23 +00:00
export default router