I would like to intercept a number passed to a route :
routes: [{ path: '/user/:id', component: User }]
And get the prop in the User
component:
export default {
props: {
id: Number
}
}
Unfortunately, I get this error:
Invalid prop: type check failed for prop "id". Expected Number with value 2, got
String with value "2".
Is there a way to natively coerce the value into a number? I looked at https://github.com/posva/vue-coerce-props but I feel I can do the same without another extension.
The usual pattern would be to use a computed property which transforms the prop into the form you'd like to use for your component. You'd also have to update the prop definition to allow both strings and numbers.
Then in the rest of your code, you'd use
parsedId
instead ofid
which admittedly isn't ideal. There's an open RFC which would solve this by allowing you to define separate internal and external names for props.Actually, for vue-router, take a look at the props function in your route definition. It should allow you to map the route params into the prop structure you desire.
I think something like this would work.