在 Vue 路由器路径中使用正则表达式

Use Regex in Vue Router Paths

我正在创建一个大量使用 vue 路由器的 VueJS 应用程序。

这是我的 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,这样它只接受作为数字的参数 (:id)。我这样做是因为 poetrysearch 受到影响,因为 /search 被视为 :id!

我试过了:

{ path: 'poetry/:id/[0-9]/g', name: 'poetrycard', component: PoetryCard }

但这不起作用。请帮忙。

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.

因此按如下方式更改您的路由定义:

{ path: 'poetry/:id(\d+)', name: 'poetrycard', component: PoetryCard }

参考- Advanced Matching patterns