Vue Router Id Param

December 16, 2019

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
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
  scrollBehavior (to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { x: 0, y: 0 }
    }
  }
})

export default router

Page Component

<template>
  <div>
    {{ $route.params.id }} == {{ id }}
  </div>
</template>

export default {
  name: 'page',
  data() {
    return {
      id: this.$route.params.id
    }
  }
}

Routing

<template>
  <div>
    <router-link to="/page/first-page">First Page</router-link>
    <router-link :to="{ name: 'page', params: {id: 'first-page'} }">First Page</router-link>
    <button @click="gotoHelloWorld">Hello World</button>
  </div>
</template>

<script>
export default {
  name: 'home',
  methods: {
    gotoHelloWorld() {
      const id = 'hello-world'
      this.$router.push({ name: 'page', params: { id } })
      // or
      // this.$router.push({ path: `/page/${id}` })
      // or router.replace
    }
  }
}
</script>
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.