Route component as props in Vue

158 views Asked by At

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.

1

There are 1 answers

0
Connor Pearson On BEST ANSWER

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.

export default {
    props: {
        id: {
            validator(value) {
                return !isNaN(parseInt(propVal));
            }
        }
    },
    computed: {
        parsedId() { 
            return parseInt(this.id); 
        }   
    }
}

Then in the rest of your code, you'd use parsedId instead of id 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.

routes: [{ 
    path: '/user/:id', 
    component: User,
    props: route => ({ id: parseInt(route.params.id) })
}]