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

Fredrik picture Fredrik · Apr 19, 2018 · Viewed 9.5k times · Source

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?

Answer

Nicholas Marshall picture Nicholas Marshall · Apr 20, 2018

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