How to Create Routes in Vue 3 using Vue Router 4

Last Updated on by in Vue JS

In this extensive guide, we will teach you how to create routing in Vue 3 js app using the Vue Router 4 package.

Routing in Vue is enabled using the additional package.

That additional package is Vue Router 4, this is a dynamic library, and helps navigate between views or components in Vue js application.

Vue Router is the official router for Vue.js. It deeply integrates with Vue.js core to make building Single Page Applications with Vue.js a breeze. Features include:

  • Nested routes mapping
  • Dynamic Routing
  • Modular, component-based router configuration
  • Route params, query, wildcards
  • View transition effects powered by Vue.js’ transition system
  • Fine-grained navigation control
  • Links with automatic active CSS classes
  • HTML5 history mode or hash mode
  • Customizable Scroll Behavior
  • Proper encoding for URLs

Throughout this tutorial, we will the basics of the routing in Vue 3. We will create a simple app and learn to enable the dynamic routing in Vue. This guide will helps us understand how to easily navigate from one view to another page in Vue.

How to Enable Routing in Vue 3 using Vue Router 4

  • Step 1: Install Vue Framework
  • Step 2: Install Vue Router
  • Step 3: Implement Bootstrap CSS
  • Step 4: Create Vue Templates
  • Step 5: Register Vue Components
  • Step 6: Define Routes in Vue
  • Step 7: Update App.vue File
  • Step 8: Run Development Server

Install Vue Framework

First install the Vue CLI, since Vue CLI is the essential tool for Vue development.

Hence, run the either of the command to the install Vue CLI:

# npm
npm install -g @vue/cli

# yarn
yarn global add @vue/cli

Once the Vue CLI is ready, go to command prompt again type, and then execute the below command.

vue create vue-mevn-stack-app

Navigate to the project directory:

cd vue-mevn-stack-app

Open the vue.config.js file and add the below code to the file. This will prevent Vue to throw multi-word error warning, .

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave: false,
})

Node.js Gatsby error – “digital envelope routines::unsupported …”

Error: digital envelope routines::unsupported

opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
library: 'digital envelope routines',
reason: 'unsupported',
code: 'ERR_OSSL_EVP_UNSUPPORTED'

Make sure to update the "scripts": [] array in package.json file.

"scripts": {
    "serve": "export NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service serve",
    "build": "export NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service build",
    "lint": "export NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service lint"
},

Implement Bootstrap CSS

We can run the given command, and install the Bootstrap UI package in Vue.

npm install bootstrap

We can now inject the bootstrap URL in the Vue app, import the below URL in the main.js file:

import 'bootstrap/dist/css/bootstrap.min.css'

Install Vue Router

With your Vue.js project set up, you can now install Vue Router. On the terminal, execute the following command:

npm install vue-router@4

Above command will install Vue Router version 4 and store it as a dependency in your project’s package.json file.

import { createApp } from "vue";
import App from "./App.vue";
import { createRouter, createWebHistory } from "vue-router";
import routes from "./routes";

const router = createRouter({
  history: createWebHistory(),
  routes,
});

const app = createApp(App);
app.use(router);
app.mount("#app");

Create Vue Templates

Let us create some components, these components will display associated data when they are clicked.

Add given code in components/UserProfile.vue file:

<template>
    <div class="row justify-content-center">
        <h3>User Profile</h3>
    </div>
</template>

<script>
export default {
    data() {
        return {
        }
    }
}
</script>

Update below code in components/Dashboard.vue file:

<template>
    <div class="row justify-content-center">
        <h3>Dashboard</h3>
    </div>
</template>

<script>
export default {
    data() {
        return {
        }
    }
}
</script>

Insert the following code in components/Contact.vue file:

<template>
    <div class="row justify-content-center">
        <h3>Contact</h3>
    </div>
</template>

<script>
export default {
    data() {
        return {
        }
    }
}
</script>

Register Vue Components

In this step we will create various components we will associate every component with their respective routes.

You have to import and register the router in the main.js file as given below:

import { createApp } from "vue";
import App from "./App.vue";
import { createRouter, createWebHistory } from "vue-router";
import routes from "./routes";

const router = createRouter({
  history: createWebHistory(),
  routes,
});

const app = createApp(App);
app.use(router);
app.mount("#app");

Define Routes in Vue

Create the routes src/routes.js file; you can define the routes as given below with the help of the Vue Router’s syntax.

import UserProfile from "./components/UserProfile.vue";
import Dashboard from "./components/Dashboard.vue";
import Contact from "./components/Contact.vue";

const routes = [
  {
    path: "/",
    component: UserProfile,
  },
  {
    path: "/dashboard",
    component: Dashboard,
  },
  {
    path: "/contact",
    component: Contact,
  },
];

export default routes;

Update App.vue File

The navigation links are set using the router-link directive, on the other hand router-view directive loads the component when the particular link is clicked.

Add the below code in App.vue file:

<template>
  <div>
    <!-- Nav bar -->
    <nav class="navbar navbar-expand-lg bg-body-tertiary">
      <div class="container">
        <a class="navbar-brand float-left">Routing in Vue 3</a>
        <ul class="nav navbar-nav flex-row float-right">
          <li class="nav-item">
            <router-link class="nav-link pr-3" to="/">User Profile</router-link>
          </li>
          <li class="nav-item">
            <router-link class="nav-link" to="/dashboard">Dashboard</router-link>
          </li>
          <li class="nav-item">
            <router-link class="nav-link" to="/contact">Contact</router-link>
          </li>
        </ul>
      </div>
    </nav>

    <!-- Router view -->
    <div class="container mt-5">
      <router-view></router-view>
    </div>
  </div>
</template>

Run Development Server

Lastly, we will use the below command to invoke the application server.

npm run serve

Once the command executed, following URL will be printed on the terminal scree:

How to Create Routes in Vue 3 using Vue Routers 4

Conclusion

In this guide we throw light on the basic part of the routing in Vue 3, however need of creating more complex routing system in Vue may also arise.

This tutorial is good to go for learning basics in Vue routing.

We have now installed and set up Vue Router 4 in your Vue.js 3 project.

We can now use Vue Router to navigate between different views/components in your application.

Reference: https://router.vuejs.org/

Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.