在Vue路由器路径中使用正则表达式 [英] Use Regex in Vue Router Paths
问题描述
我正在创建一个大量使用vue路由器的VueJS应用.
I am creating a VueJS app which heavily uses the vue router.
这是我的 routes.js
的结构:
export const routes = [
{ path: '', component: Poetry, children: [
{ path: '', name: 'poetry', component: PoetryLanding },
{ path: 'poetry/:id', name: 'poetrycard', component: PoetryCard },
{ path: 'poetry/search', name: 'poetrysearch', component: PoetrySearch },
]},
]
我想在第二个子组件(即 poetrycard
)中使用正则表达式,以便它仅接受为数字的params(:id
).我这样做是因为 poetrysearch
受到影响,因为/search
被视为:id
!
I want to use regex in second child component i.e. poetrycard
such that it only accepts the params(:id
) which is a number. I am doing this because poetrysearch
gets affected as /search
is treated as :id
!
我尝试过:
{ path: 'poetry/:id/[0-9]/g', name: 'poetrycard', component: PoetryCard }
但这不起作用.请帮忙.
But this doesn't work. Please help.
推荐答案
vue-router使用 path-to-regexp 作为其路径匹配引擎,因此它支持许多高级匹配模式,例如可选的动态细分,零个或多个/一个或多个需求,甚至是自定义的正则表达式模式.
vue-router uses path-to-regexp as its path matching engine, so it supports many advanced matching patterns such as optional dynamic segments, zero or more / one or more requirements, and even custom regex patterns.
因此,如下更改路由定义:
So change your route definition as follows:
{ path: 'poetry/:id(\\d+)', name: 'poetrycard', component: PoetryCard }
参考资料-高级匹配模式
这篇关于在Vue路由器路径中使用正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!