88 lines
2.3 KiB
JavaScript
88 lines
2.3 KiB
JavaScript
import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'
|
||
import { setupRouterGuard } from './guard'
|
||
import { basicRoutes, EMPTY_ROUTE, NOT_FOUND_ROUTE } from './routes'
|
||
import { getToken, isNullOrWhitespace } from '@/utils'
|
||
import { usePermissionStore } from '@/store'
|
||
|
||
const isHash = false
|
||
export const router = createRouter({
|
||
history: isHash ? createWebHashHistory('/') : createWebHistory('/'),
|
||
routes: basicRoutes,
|
||
scrollBehavior: () => ({ left: 0, top: 0 }),
|
||
})
|
||
|
||
export async function setupRouter(app) {
|
||
await addDynamicRoutes()
|
||
setupRouterGuard(router)
|
||
app.use(router)
|
||
}
|
||
|
||
export async function addDynamicRoutes() {
|
||
const token = getToken()
|
||
|
||
// 没有token情况
|
||
if (isNullOrWhitespace(token)) {
|
||
router.addRoute(EMPTY_ROUTE)
|
||
return
|
||
}
|
||
|
||
// 有token的情况
|
||
try {
|
||
const permissionStore = usePermissionStore()
|
||
const accessRoutes = permissionStore.generateRoutes()
|
||
|
||
// 确保路由按正确顺序添加
|
||
accessRoutes.forEach((route) => {
|
||
if (!router.hasRoute(route.name)) {
|
||
router.addRoute(route)
|
||
}
|
||
})
|
||
|
||
// 移除空路由,添加404路由
|
||
if (router.hasRoute(EMPTY_ROUTE.name)) {
|
||
router.removeRoute(EMPTY_ROUTE.name)
|
||
}
|
||
router.addRoute(NOT_FOUND_ROUTE)
|
||
|
||
// 确保根路径重定向到工作台
|
||
// if (!router.hasRoute('workbench')) {
|
||
// const workbenchRoute = {
|
||
// name: 'workbench',
|
||
// path: '/',
|
||
// component: () => import('@/views/workbench/index.vue'),
|
||
// redirect: '/workbench',
|
||
// // children: [
|
||
// // {
|
||
// // name: 'Workbench',
|
||
// // path: 'workbench',
|
||
// // component: () => import('@/views/workbench/index.vue'),
|
||
// // meta: {
|
||
// // title: '工作台',
|
||
// // icon: 'mdi:index',
|
||
// // order: 0,
|
||
// // },
|
||
// // },
|
||
// // ],
|
||
// }
|
||
// router.addRoute(workbenchRoute)
|
||
// }
|
||
|
||
// console.log(router)
|
||
} catch (error) {
|
||
console.error(error)
|
||
throw error
|
||
}
|
||
}
|
||
|
||
export function getRouteNames(routes) {
|
||
return routes.map((route) => getRouteName(route)).flat(1)
|
||
}
|
||
|
||
function getRouteName(route) {
|
||
const names = [route.name]
|
||
if (route.subMenu && route.subMenu.length) {
|
||
names.push(...route.subMenu.map((item) => getRouteName(item)).flat(1))
|
||
}
|
||
return names
|
||
}
|