3. Routing

In the previous chapter, we set up our Vue JS app. In this chapter, we are going to set the routing of our application. Routing means which component should be loaded when a specific URL is accessed. Vue JS runs on components, each page you see in a SPA is a component.

Video tutorial (routing):

For this purpose, first, let’s install the routing library. Run the following command in your CMD opened in the web folder:

> npm install vue-router

Then open your web/src/main.js file and paste the following lines in it:

// import the vue router necessary functions
import { createRouter, createWebHistory } from 'vue-router'

There are a lot of other functions too in the vue-router library, but we need only 2, so we are importing only the methods we need. Then you need to create an array where we will define all our components and their paths.

// Define some routes
// Each route should map to a component.
const routes = [

We will define our components and their path in this array. Once they are defined, Vue JS will automatically render the component when that path is accessed from the URL.

Then we need to create a routes object that will create a router instance.

// Create the router instance and pass the `routes` option
// You can pass in additional options here, but let's
// keep it simple for now.
const router = createRouter({
    // Provide the history implementation to use. We are using the hash history for simplicity here.
    history: createWebHistory(),
    routes, // short for `routes: routes`

After that, we need to tell our Vue JS app to use these routing. So, replace the following lines:


With the following:

const app = createApp(App)

At this point, you will see no change in the output because we haven’t defined any route yet.

You can learn more about routing in Vue JS from their official site.