Vue.js Router

December 11, 2019

Install

npm install vue-router

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
  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  }
]

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

Edit main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'

Vue.config.productionTip = false

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

App Component

<template>
  <div id="app">
    <router-link to="/about">About</router-link>
    <router-link :to="{ name: 'about' }">About</router-link>
    <router-view/>
  </div>
</template>

Page Component

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

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

Home Component

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

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.