import { createRouter, createWebHistory } from 'vue-router'; import Home from '../pages/home/index.vue'; import Login from '../pages/login/index.vue'; import UserManage from '../pages/usermanage/index.vue'; import ComManage from '../pages/commanage/index.vue'; import ScopeManage from '../pages/scopemanage/index.vue'; import User from '../pages/user/index.vue'; import SwitchSelection from '../pages/switchselection/index.vue'; import PanelSelection from '../pages/panelselection/index.vue'; import Log from '../pages/log/index.vue'; import DicManage from '../pages/dicmanage/index.vue'; const routes = [ { path: '/', // 动态重定向到登录页或主页 redirect: () => { const isAuthenticated = localStorage.getItem('token'); return isAuthenticated ? '/home' : '/login'; } }, { path: '/login', name: '登录', component: Login }, { path: '/home', name: '主页', component: Home, meta: { requiresAuth: true } // 需要认证的路由 }, { path: '/log', name: '日志中心', component: Log, meta: { requiresAuth: true } // 需要认证的路由 }, { path: '/usermanage', name: '用户管理', component: UserManage, meta: { requiresAuth: true } // 需要认证的路由 }, { path: '/commanage', name: '组织管理', component: ComManage, meta: { requiresAuth: true } // 需要认证的路由 }, { path: '/scopemanage', name: '权限管理', component: ScopeManage, meta: { requiresAuth: true } // 需要认证的路由 }, { path: '/dicmanage', name: '字典管理', component: DicManage, meta: { requiresAuth: true } // 需要认证的路由 }, { path: '/user', name: '个人中心', component: User, meta: { requiresAuth: true } // 需要认证的路由 }, { path: '/switchselection', name: '开关选型', component: SwitchSelection, meta: { requiresAuth: true } // 需要认证的路由 }, { path: '/panelselection', name: '开关选型', component: PanelSelection, meta: { requiresAuth: true } // 需要认证的路由 }, { path: '/:pathMatch(.*)*', name: '404错误', component: () => import('../pages/404/index.vue') // 404页面 }, ]; const router = createRouter({ history: createWebHistory(), routes }); // 路由守卫 router.beforeEach((to, from, next) => { const isAuthenticated = localStorage.getItem('token') // 用localStorage存储token const username = localStorage.getItem('username') // 获取用户名 if (to.meta.requiresAuth && !isAuthenticated) { // 如果需要认证且没有token,则跳转到登录页面 next('/login') } else if ((to.path == '/usermanage' || to.path == '/scopemanage') && (username != 'Admin' && username != 'MoMoWen')) { // 如果访问的是用户管理页面但用户名不是Admin,则跳转到主页 next('/home') } else { // 其他情况正常放行 sessionStorage.setItem('currentRoute', to.fullPath) next() } }) export default router;