Defining Vue.js Router Routes with Regular Expressions

— 3 minute read


We all know that we can define parameters on Vue Router route paths which are then parsed and made available in the $route.params object. We can take this a step further by restricting the patterns that these parameters take by using a regular expression.

This has a couple of benefits - it pre-validates the parameter so we only reach the route with a correct parameter value, and it also allows us to differentiate between routes that would otherwise be ambiguous.

Take this route as an example:

{
path: '/users',
component: UserWrapper
children: [
{
path: ':page',
component: UsersList
},
{
path: ':id',
component: UserDetails
},
]
}

I'm going to replace a Guid with a smaller string "a-b-c-d-e" to keep things a little more succinct!

This definition means we would want to navigate to a path like users/a-b-c-d-e to view that specific User, or go to users/3 to see page 3 of Users. The problem is that the users/a-b-c-d-e URL would always match the first route - because it thinks "a-b-c-d-e" is the page parameter.

If our ID value was always a Guid and our page number always a number then we can restrict the :page parameter to only match when that part of the URL is recognised as a number. We do this by appending a Regular Expression to the parameter definition which defines how the parameter should be matched.

{
path: '/users',
component: UserWrapper
children: [
{
path: ':page(\d+)', // match 1 or more numbers
component: UsersList
},
{
path: ':id',
component: UserDetails
}
]
}

With this regex in place users/a-b-c-d-e won't match the first route because the Guid is not a number, it will instead fall through to the second one where it will match.

Similarly, users/3 will match the first route because "3" is a number.

Filed under