【问题标题】:Use Regex in Vue Router Paths在 Vue 路由器路径中使用正则表达式
【发布时间】:2018-12-20 11:51:13
【问题描述】:

我正在创建一个大量使用 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 }

但这不起作用。请帮忙。

【问题讨论】:

    标签: javascript vue.js vue-router


    【解决方案1】:

    vue-router 使用path-to-regexp 作为其路径匹配引擎,因此它支持许多高级匹配模式,例如可选的动态段、零个或多个/一个或多个要求,甚至自定义正则表达式模式。

    所以改变你的路线定义如下:

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

    参考-Advanced Matching patterns

    【讨论】:

    • 感谢您的回答,但它不起作用!页面根本没有加载。
    • @Sanjay 你能试试用\\d+替换正则表达式吗
    • 如果有人想知道 - 这也适用于 Vue 路由器别名,例如。 {path: '/abc/:type?', alias: '/something-different/:type?'}
    猜你喜欢
    • 2019-01-28
    • 1970-01-01
    • 2020-09-25
    • 1970-01-01
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    • 2020-05-22
    • 2011-11-05
    相关资源
    最近更新 更多