路由配置守卫
VTS 基于 Vue Router
提供了灵活的路由管理和权限控制机制,确保应用的安全性和可维护性。
1. 路由
路由配置
所有的子路由均在 child-routes.ts
文件中配置,支持嵌套路由、动态路由和按需加载。
ts
const importModule = import.meta.glob('../modules/**/*.vue')
const childRoutes: Array<RouteRecordRaw> = [
{
path: 'test-layout',
name: '布局测试',
meta: {
title: 'TestLayout'
},
component: LayoutArea
},
{
path: 'user',
component: Layout,
name: 'User',
meta: {
title: '账户'
},
redirect: {
name: 'UserLogin'
},
children: [
{
path: 'login',
name: 'UserLogin',
component: importModule['../modules/UserAccount/pages/login.vue'],
meta: {
title: '登录'
}
}
]
},
{
path: 'project',
component: Layout,
name: 'Project',
redirect: {
name: 'ProjectList'
},
children: [
{
path: '',
name: 'ProjectList',
meta: {
title: '项目列表'
},
component: importModule['../modules/Project/pages/list.vue']
},
{
path: 'list',
name: 'ProjectList',
component: importModule['../modules/Project/pages/list.vue'],
meta: {
title: '项目管理'
}
}
]
},
{
path: 'result',
redirect: {
name: 'ProjectList'
}
},
{
path: 'result/:projectId',
component: LayoutView,
name: 'result',
redirect: {
name: 'ResultOverview'
},
children: [
{
path: 'overview',
name: 'ResultOverview',
component: importModule['../modules/Result/pages/overview.vue'],
meta: {
title: '总览'
}
}
]
}
]
export default childRoutes
路由特性
- 嵌套路由:支持灵活的嵌套结构,便于组织复杂页面。
- 路由懒加载:使用
import.meta.glob
实现按需加载,提高性能。 - 动态路由:支持参数化路由,
/result/:projectId
形式的动态匹配。
2. 鉴权
路由权限控制在 permission.ts
中实现,确保用户只能访问授权页面。
权限守卫
ts
export function createRouterGuards(router: Router) {
router.beforeEach(async (to, from, next) => {
NProgress.start()
document.title = `${ to.meta.title || '' } - ${ systemTitle }`
const currentRouteLocale = to.params.locale
if (
allowlist.find(
name => to.name === name
)
) {
next()
return
}
if (!Cookie.get('token')) {
next(`/${ currentRouteLocale || store.state.UserAccount.locale }/user/login`)
return
}
// 获取用户信息
const { data, error } = await store.dispatch('UserAccount/getUserInfo')
if (error) {
store.dispatch('UserAccount/setLanguage', {
locale: currentRouteLocale || data.language || store.state.UserAccount.locale
})
Cookie.remove('token')
next(`/${ currentRouteLocale || store.state.UserAccount.locale }/user/login`)
return
}
store.dispatch('UserAccount/setLanguage', {
locale: currentRouteLocale || data.language
})
next()
})
router.afterEach((to) => {
NProgress.done()
})
}
鉴权机制
- 白名单机制:
allowlist
允许部分页面无需登录即可访问。 - Token 验证:如果
token
不存在,用户会被重定向至登录页面。 - 用户信息获取:从
store
获取用户信息,决定是否允许访问。 - 进度条增强体验:使用
NProgress
提示页面切换状态。