124 lines
2.5 KiB
JavaScript
124 lines
2.5 KiB
JavaScript
import { createRouter, createWebHashHistory } from 'vue-router'
|
||
import Login from '@/views/Login.vue'
|
||
import Page404 from '@/views/error/404.vue'
|
||
import Layout from '@/components/Layout/index.vue'
|
||
import Dashboard from '@/views/desktop/index.vue'
|
||
import bigScreen from '@/views/screen/index.vue'
|
||
|
||
const modules = import.meta.glob('../views/**/index.vue', {
|
||
eager: false,
|
||
import: 'default'
|
||
})
|
||
|
||
const generateRoutes = () => {
|
||
const routes = []
|
||
|
||
Object.entries(modules).forEach(([filePath, module]) => {
|
||
const excludePaths = [
|
||
'views/Login.vue',
|
||
'views/desktop/index.vue',
|
||
'views/error/',
|
||
'views/screen/',
|
||
]
|
||
if (excludePaths.some(path => filePath.includes(path))) {
|
||
return
|
||
}
|
||
|
||
const routePath = filePath
|
||
.replace('../views', '')
|
||
.replace('.vue', '')
|
||
.toLowerCase()
|
||
|
||
const routeName = routePath
|
||
.split('/')
|
||
.filter(Boolean)
|
||
.map(seg => seg.charAt(0).toUpperCase() + seg.slice(1))
|
||
.join('')
|
||
|
||
routes.push({
|
||
path: routePath,
|
||
name: routeName || 'SystemRoleIndex',
|
||
component: module
|
||
})
|
||
})
|
||
|
||
return routes
|
||
}
|
||
|
||
const routes = [
|
||
{
|
||
path: '/login',
|
||
name: 'Login',
|
||
component: Login,
|
||
meta: { isPublic: true }
|
||
},
|
||
{
|
||
path: '/bigScreen',
|
||
name: 'bigScreen',
|
||
component: bigScreen,
|
||
meta: { requiresAuth: true }
|
||
},
|
||
{
|
||
path: '/',
|
||
redirect: '/login'
|
||
},
|
||
{
|
||
path: '/layout',
|
||
component: Layout,
|
||
meta: { requiresAuth: true },
|
||
children: [
|
||
{
|
||
path: '/dashboard',
|
||
name: 'Dashboard',
|
||
component: Dashboard
|
||
},
|
||
...generateRoutes()
|
||
]
|
||
},
|
||
{
|
||
path: '/:pathMatch(.*)*',
|
||
name: 'Page404',
|
||
component: Page404
|
||
}
|
||
]
|
||
|
||
const router = createRouter({
|
||
history: createWebHashHistory(import.meta.env.BASE_URL || './'),
|
||
routes,
|
||
scrollBehavior() {
|
||
return { top: 0 }
|
||
}
|
||
})
|
||
|
||
// 优化路由守卫:适配hash模式,增强容错
|
||
router.beforeEach((to, from, next) => {
|
||
// 1. 公开页面直接放行(登录页)
|
||
if (to.meta.isPublic) {
|
||
next()
|
||
return
|
||
}
|
||
|
||
// 2. 非公开页面校验token(兼容hash模式)
|
||
try {
|
||
const token = localStorage.getItem('token')
|
||
const isValidToken = token.trim().length > 0
|
||
|
||
if (isValidToken) {
|
||
next()
|
||
} else {
|
||
next({
|
||
path: '/login',
|
||
query: { redirect: to.fullPath },
|
||
replace: true
|
||
})
|
||
}
|
||
} catch (error) {
|
||
console.error('路由守卫校验失败:', error)
|
||
next({
|
||
path: '/login',
|
||
replace: true
|
||
})
|
||
}
|
||
})
|
||
|
||
export default router |