8

I am creating a VueJS app which heavily uses the vue router.

Here's the structure of my 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 },
    ]},
]

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!

I tried:

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

But this doesn't work. Please help.

1 Answer 1

23

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 }

Reference- Advanced Matching patterns

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the answer but it doesn't work! The page doesn't load at all.
@Sanjay can you try replacing the regex with \\d+
If anyone is wondering - this also applies to Vue Router aliases eg. {path: '/abc/:type?', alias: '/something-different/:type?'}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.