Vue3路由参数类型校验:限制参数为指定集合值
Vue3路由参数限制为指定集合的实现方案
你可以通过两种方式实现路由参数的强制校验,无需在组件内做判断:
方法一:使用正则匹配路径(推荐)
利用Vue Router支持在路由参数中嵌入正则表达式的特性,直接限制id只能匹配people数组中的值。不符合的路径会自动落入404路由。
实现步骤:
- 动态生成正则匹配字符串
- 修改路由的
path配置
const people = ['mary', 'bob', 'pat'] as const; type tPersonId = typeof people[number]; // 生成正则匹配分支,结果为"mary|bob|pat" const personIdPattern = people.join('|'); const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), strict: true, routes: [ { path: '/', name: 'home', component: HomeView, }, { // 用正则限制id只能是指定值 path: `/person/:id(${personIdPattern})`, name: 'person', component: () => import('@/views/PersonView.vue'), // 可选:给路由参数添加TypeScript类型约束 meta: { params: {} as { id: tPersonId } } }, { path: '/:pathMatch(.*)*', name: '404', component: NotFoundView, } ] });
这样,/person/bob会正常匹配到person路由,而/person/jennifer会直接被404路由捕获。
方法二:使用路由前置守卫(beforeEnter)
通过路由的beforeEnter钩子在进入路由前校验参数,不符合则跳转到404。
const people = ['mary', 'bob', 'pat'] as const; type tPersonId = typeof people[number]; const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), strict: true, routes: [ { path: '/', name: 'home', component: HomeView, }, { path: '/person/:id', name: 'person', component: () => import('@/views/PersonView.vue'), beforeEnter: (to) => { // 校验id是否在指定集合中 if (!people.includes(to.params.id as tPersonId)) { // 跳转到404路由,并传递当前路径作为参数 return { name: '404', params: { pathMatch: to.path.split('/').slice(1) } }; } } }, { path: '/:pathMatch(.*)*', name: '404', component: NotFoundView, } ] });
两种方案对比:
- 正则路径方案:更高效,不符合的路径不会触发person路由的任何逻辑,直接走404,适合静态固定的参数集合。
- 路由守卫方案:更灵活,如果参数集合需要动态更新(比如从接口获取),可以在守卫中动态校验。
内容的提问来源于stack exchange,提问作者Colin
相关产品推荐
相关产品推荐

