Vue Router: how to cast params as integers instead of strings?
You have to handle casting any params values yourself. In the route object define a props function. Here is an example:
{
path: '/user/:userId',
component: UserProfile,
props: (route) => {
const userId = Number.parseInt(route.params.userId, 10)
if (Number.isNaN(userId)) {
return 0
}
return { userId }
}
}
link to vue router docs this is under Function mode
I'm probably late to the party, but this is my take on this. I wrote a function that returns a function that casts route params values to the props with same name with the given type.
function paramsToPropsCaster(mapping) {
return function(route) {
let nameType = Object.entries(mapping); // [[param1, Number], [param2, String]]
let nameRouteParam = nameType.map(([name, fn]) => [name, fn(route.params[name])]); // [[param1, 1], [param2, "hello"]]
let props = Object.fromEntries(nameRouteParam); // {param1: 1, param2: "hello"}
return props;
}
}
And then, in your route definition:
{
path: '/projects/:param1/editor/:param2',
component: ProjectEditor,
name: 'project-editor',
props: paramsToPropsCaster({'param1': Number, 'param2': String}),
}
This is just a hint on what you can do to solve the problem asked here, don't use this verbatim!