Vue Router Cast Param to Integer/Number

Feb 8, 2020

By default, Vue Router Param is String (as it is usually pass in via URL).

Option 1: Cast to Number in Component

<div>    {{ pageNumber }}</div>export default {  name: 'page',  data() {    return {      pageNumber: parseInt(this.$route.params.id)    }  }}

Option 2: Use Vue Router Props

Edit router/index.js

import Vue from 'vue'import VueRouter from 'vue-router'import Home from '../views/Home.vue'import Page from '../views/Page.vue'Vue.use(VueRouter)const routes = [  {    path: '/',    name: 'home',    component: Home  },  {    path: '/page/:id',    component: Page,    props(route) {      return {        pageNumber: parseInt(route.params.id)      }    }  }]const router = new VueRouter({  mode: 'history',  base: process.env.BASE_URL,  routes})export default router

NOTE: Props doesn't create this.$route.params.pageNumber, but send the params as components props.

Page.vue

<div>    This is Number: {{ pageNumber }}    This is String: {{ $route.params.id }}</div>export default {  name: 'page',  props: {    pageNumber: Number // from router  }}

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.