POST POST

FEB
18
2022

Parsing Vue Router Path Parameters

ORIGINALLY POSTED TO: https://blog.simontimms.com/2022/02/18/parsing-vue-router-parameters

In the vue router you can set up path parameters that are bound into the rendered component. For instance you might have a route like this:

1
2
3
4
5
6
{
path: '/reports/:reportId/:reportName/:favorite',
name: 'Reports',
component: ReportView,
props: true
}

This will bind the parameters reportId, reportName and favorite on the component. However when you drop into that component and look at the values passed in you will see that they are strings. Of course that makes sense, the router doesn't really know if the things you pass in are strings or something else. Consider the route /reports/17/awesome report/false. Here reportId and favorite are going to be strings.

You can work around that by giving props in the router a function rather than just a boolean.

1
2
3
4
5
6
7
8
9
10
{
path: '/reports/:reportId/:reportName/:favorite',
name: 'Reports',
component: ReportView,
props: (route) => ({
...route.params,
reportId: parseInt(route.params.reportId),
favorite: route.params.favorite === 'true',
})
}

Simon Timms

Email Email
Web Web
Twitter Twitter
GitHub GitHub
RSS

Looking for someone else?

You can find the rest of the Western Devs Crew here.

© 2015 Western Devs. All Rights Reserved. Design by Karen Chudobiak, Graphic Designer