Search⌘ K
AI Features

Installing Vue Router

Explore how to install Vue Router in your Vue 3 project using npm or Vue CLI. Learn to set up router configuration, create route mappings to components, and integrate routing into your app. Understand route history modes and how to update your main app files to use Vue Router for navigation.

Installing Vue Router

The router can be easily added to our app from Vue CLI or via npm by running the following command:

npm install vue-router

Let’s install the router ourselves via npm and run through the steps needed to get a basic example up and running.

If you haven’t already, use Vue CLI to create a new project based on the “default” preset. After it has finished installing, change the directory into the project’s root folder and run the following command:

npm install vue-router@4

Once the router library is installed, we need to configure it and add some routes to map URLs to components. Let’s create a file called router.js inside the src folder and add the following code:

Javascript (babel-node)
import { createRouter, createWebHistory } from "vue-router";
import Home from "./views/Home.vue";
const routes = [
{
path: "/",
name: "home",
component: Home
}
];
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;

We start by importing the createRouter() and createWebHistory() methods from the vue-router package, along with a Home component that we’ll be routing to (we’ll create this in a moment).

Next, we create a routes array. This should ...