我想为我的应用程序设置路由,以便参数只能来自一组给定值。
在我的代码中的某个地方我有一个像这样的数组:
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'),
},
{
path: '/:pathMatch(.*)*',
name: '404',
component: NotFoundView,
}
]
});
我想强制
:id
的值只能是我的 people
数组中的名称之一和/或可以键入为 tPersonId
(因此我不需要在我的PersonView 组件)。结果应该是 /person/bob
是有效路线,但 /person/jennifer
不是(并且被 404 路线捕获)。
要将
:id
参数值限制为 people
数组中的名称,并针对任何“不允许的”值重定向到 404 页面,您可以将全局 routeguard 与 Vue Router 结合使用。
配置您的路由器并添加全局 beforeEarch 防护:
const router = createRouter({
routes: [
// your routes
]
});
// Now the navigation guard
router.beforeEach((to, from, next) => {
if(to.path.startsWith('/person/')) {
const id = to.params.id;
if(people.includes(id)) {
next(); // if the id is in the array, continue with the route
} else {
next('/404');
}
} else {
next(); // For any other route
}
});
此代码应检查当前路线是否以
/person/
开头,以及 id
是否在您的 people
数组内。如果 id
有效,则允许继续导航。
希望这对您有帮助!