BeginnerCoder
intermediate#vue.js#vue router#client-side routing

Using Vue Router for Client-Side Routing

This article was AI-drafted and has not been reviewed yet. Spotted a mistake? Tell us.

Learn how to use Vue Router for client-side routing in your Vue.js application.

Introduction to Vue Router

In this tutorial, we will learn how to use Vue Router for client-side routing in our Vue.js application. Vue Router is the official router for Vue.js and it provides a simple and flexible way to manage client-side routing.

Step 1: Installing Vue Router

First, we need to install Vue Router. We can do this by running the following command in our terminal:

npm install vue-router

Step 2: Creating Routes

Next, we need to create routes for our application. We can do this by creating a new file called router.js in the src directory:

// src/router.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from './views/Home.vue'
import About from './views/About.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'home',
    component: Home
  },
  {
    path: '/about',
    name: 'about',
    component: About
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router

Step 3: Using Routes in Our Application

Now, we can use our routes in our application. We can do this by importing the router in our main.js file and using the router-view component in our App.vue file:

// src/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')
// src/App.vue
<template>
  <div>
    <nav>
      <ul>
        <li><router-link to='/'>Home</router-link></li>
        <li><router-link to='/about'>About</router-link></li>
      </ul>
    </nav>
    <router-view></router-view>
  </div>
</template>
Keep going with vue.js

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.