How to create Vue routes

Prerequisite: You have to have the Vue Router installed, if not, read on how to do so here.


Add routes to switch between components in SPA (Single page application), or switch between pages (as the term goes for regular websites which does a page reload).

Go to main.js , then:

  1. Create routes and store them in an array constant.
const routes = []

2. The array takes objects with 2 properties

  • path matching, and
  • its respective component to where the route will go to.
const routes = [
{path: '/', component: HomePage},
{path: '/services', component: Services}

3. Import components

import HomePage from './components/HomePage.vue'
import Services from './components/Services.vue'

4. Instantiate router. This is already done in the router constant - See code here.

5. To switch between routes, modify the navigation in the Header component, using router-link tag for navigation instead of the href attribute. Also, use to attribute to direct the path to the specific component

<router-link to="/"><a ..>home</a><router-link>
<router-link to="/menu"><a ..>menu</a><router-link>

6. Displaying the router: go to App.vue and use router-view tag instead of home, service , etc tags except for the header and footer. Also remove the importation of the said components, as they will be used only through routing now

Here is full code in main.js

import { createApp } from 'vue'
import {createRouter, createWebHistory} from 'vue-router'
import HomePage from './components/HomePage.vue'
import Services from './components/Services.vue'

import App from './App.vue'
# Define some routes
const routes = [
{ path: '/', component: HomePage },
{ path: '/services', component: Services }

# Create the router instance and pass the `routes` options
const router = createRouter({
# Provide the history implementation to use.
history: createWebHistory(),
routes, // short for `routes: routes`

Your routes should be working. If something doesn’t work, please ask in the comment and I will get back to you (or anyone else).

Other topics on Vue Routing:

  • History
  • Named routes
  • Binding & Dynamic Routes
  • Redirecting & Catching errors
  • Nested routes/links
  • Vue Router navigation methods: go ,replace,push
  • Global Navigation guards: before , after
  • In-component guards: beforeRouteEnter , update and leave
  • Scrolling back to pages positions during page navigation: scrollBehavior to different routes/links and also using back and forward buttons from the browser and also scroll location.

Happy coding!



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store