0
0
VueHow-ToBeginner · 3 min read

How to Install Vue Router: Step-by-Step Guide

To install vue-router in a Vue 3 project, run npm install vue-router@4 or yarn add vue-router@4. Then import and configure it in your Vue app to enable routing.
📐

Syntax

Use the following command to install Vue Router version 4, which is compatible with Vue 3:

  • npm install vue-router@4 - installs using npm
  • yarn add vue-router@4 - installs using yarn

After installation, import Vue Router in your main JavaScript file and create a router instance with routes.

bash
npm install vue-router@4
💻

Example

This example shows how to install Vue Router and set up a simple router with two pages: Home and About.

javascript
import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'

const Home = { template: '<div>Home Page</div>' }
const About = { template: '<div>About Page</div>' }

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

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

const app = createApp({})
app.use(router)
app.mount('#app')
Output
The app renders a page showing 'Home Page' at '/' and 'About Page' at '/about' with navigation handled by Vue Router.
⚠️

Common Pitfalls

Common mistakes when installing or using Vue Router include:

  • Installing the wrong version (Vue Router 3 is for Vue 2, use version 4 for Vue 3).
  • Not calling app.use(router) before mounting the app.
  • Forgetting to import createRouter and createWebHistory from vue-router.
  • Not defining routes properly as an array of objects with path and component.
bash
/* Wrong: Using Vue Router 3 with Vue 3 */
npm install vue-router

/* Right: Use version 4 for Vue 3 */
npm install vue-router@4
📊

Quick Reference

  • Install with npm install vue-router@4 or yarn add vue-router@4.
  • Import createRouter and createWebHistory from vue-router.
  • Create routes as an array of objects with path and component.
  • Use app.use(router) before mounting your Vue app.

Key Takeaways

Always install Vue Router version 4 for Vue 3 projects using npm or yarn.
Import and configure Vue Router with createRouter and createWebHistory before mounting the app.
Define routes as an array of objects with path and component properties.
Call app.use(router) to enable routing in your Vue app.
Avoid mixing Vue Router versions to prevent compatibility issues.