Vue Routing

Vue Tutorial

🚦 Vue Routing (Vue Router)

Vue Routing allows you to build Single Page Applications (SPA) where navigation happens without reloading the page.

Routing in Vue.js is handled using Vue Router.


1️⃣ What is Routing in Vue? ⭐

Routing means:

  • Mapping URL paths to Vue components

  • Changing views without page refresh

  • Essential for SPA development

📌 Example:

/home → Home.vue
/about → About.vue

2️⃣ What is Vue Router? ⭐⭐

  • Official routing library for It

  • Manages URLs & components

  • Supports:

    • Dynamic routes

    • Nested routes

    • Route guards

    • Lazy loading


3️⃣ Installing Vue Router ⭐

Vue 3

npm install vue-router

4️⃣ Basic Router Setup ⭐⭐

📁 router/index.js

import { createRouter, createWebHistory } from "vue-router";
import Home from "../views/Home.vue";
import About from "../views/About.vue";
const routes = [
{ path: “/”, component: Home },
{ path: “/about”, component: About }
];const router = createRouter({
history: createWebHistory(),
routes
});

export default router;


5️⃣ Register Router in App ⭐

main.js

import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
createApp(App).use(router).mount(“#app”);

6️⃣ <router-view> and <router-link> ⭐⭐⭐

Router View

<router-view />

📌 Displays matched component


Router Link

<router-link to="/about">About</router-link>

📌 SPA navigation (no reload)


7️⃣ Dynamic Routing ⭐⭐

{
path: "/user/:id",
component: User
}

Access Parameter

this.$route.params.id

📌 URL: /user/10


8️⃣ Nested Routes ⭐⭐⭐

{
path: "/dashboard",
component: Dashboard,
children: [
{ path: "profile", component: Profile },
{ path: "settings", component: Settings }
]
}

📌 URL:

  • /dashboard/profile

  • /dashboard/settings


9️⃣ Programmatic Navigation ⭐⭐

this.$router.push("/home");

With Params

this.$router.push({ name: "user", params: { id: 5 } });

🔟 Route Guards (Security) ⭐⭐⭐

Global Guard

router.beforeEach((to, from, next) => {
if (to.meta.auth && !isLoggedIn) {
next("/login");
} else {
next();
}
});

📌 Used for:

  • Authentication

  • Authorization


1️⃣1️⃣ Lazy Loading Routes ⭐⭐

{
path: "/about",
component: () => import("../views/About.vue")
}

📌 Improves performance


1️⃣2️⃣ History Modes ⭐⭐

Mode Description
createWebHistory() Clean URLs (/about)
createWebHashHistory() Hash URLs (#/about)

📌 Interview Questions

Q1. What is Vue Router?
👉 Official routing library for Vue

Q2. What is <router-view>?
👉 Renders matched component

Q3. Difference between router-link & <a>?
👉 router-link avoids reload

Q4. What are route guards?
👉 Control navigation access


✅ Summary

✔ Vue Router enables SPA navigation
✔ Routes map URL → components
<router-view> renders components
✔ Supports dynamic & nested routes
✔ Route guards handle security
✔ Lazy loading improves speed

You may also like...