When I enter a URL using the browser field, the params are cast as strings, rather than an integer, e.g. /user/1
returns {id: "1"}
. However, when when using this.$route.push({})
, the params are, correctly, cast as integers {id: 1}
.
Is this behavior intended? If not, how do I fix it?
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With