Installing Vue Router
Vue Router is the official routing library that maps URLs to components.
In this page:
Syntax
npm install vue-router@4
Installing Vue Router
In a project install it with npm install vue-router@4, or add it while scaffolding with create-vue. Create a router with createRouter and a history mode, then register it with app.use(router). From the CDN it is available as the VueRouter global.
Note:
Choose createWebHistory for clean URLs or createWebHashHistory when you cannot configure the server.
Example: Installing Vue Router
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
$ npm install vue-router@4
// main.js
import { createApp } from "vue";
import { createRouter, createWebHistory } from "vue-router";
import App from "./App.vue";
const router = createRouter({ history: createWebHistory(), routes: [] });
createApp(App).use(router).mount("#app");
</body>
</html>
⚠️ Run this in your own terminal or Node.js environment.
Live Example
Related Topics
Common Mistakes
- Installing vue-router 3 for Vue 3
- Forgetting app.use(router)
- Using web history without server fallback rules
Chapter Summary
- npm install vue-router@4
- createRouter builds the router
- app.use(router) installs it
- Pick a history mode
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: