Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue Router: how to cast params as integers instead of strings?

Tags:

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?

like image 381
Fredrik Avatar asked Apr 19 '18 15:04

Fredrik


2 Answers

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

like image 187
Nicholas Marshall Avatar answered Sep 24 '22 19:09

Nicholas Marshall


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!

like image 22
pongi Avatar answered Sep 21 '22 19:09

pongi