Vue Router
Vue.js Development
Vue Router
Vue Router is the official routing library for Vue.js that enables you to build single-page applications with client-side navigation. When users click links or navigate programmatically, Vue Router updates the URL and renders the appropriate component without a full page reload. It supports dynamic route matching, nested routes, navigation guards for access control, and lazy loading for performance. Vue Router integrates deeply with Vue's reactivity system, making route parameters and query strings reactive properties that trigger re-renders when they change.
Setting Up Vue Router
Install Vue Router and configure it with an array of route definitions that map URL paths to components.
// router/index.js
import { createRouter, createWebHistory } from "vue-router";
import HomeView from "../views/HomeView.vue";
import AboutView from "../views/AboutView.vue";
const routes = [
{ path: "/", name: "home", component: HomeView },
{ path: "/about", name: "about", component: AboutView },
// Lazy-loaded route (code-split into separate chunk)
{
path: "/dashboard",
name: "dashboard",
component: () => import("../views/DashboardView.vue"),
},
];
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;
// main.js
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
createApp(App).use(router).mount("#app");
Router Links and Views
Use <RouterLink> for navigation and <RouterView> to render the matched component. RouterLink generates accessible anchor tags with active class management.
<!-- App.vue -->
<template>
<nav>
<RouterLink to="/">Home</RouterLink>
<RouterLink to="/about">About</RouterLink>
<RouterLink :to="{ name: 'dashboard' }">Dashboard</RouterLink>
</nav>
<!-- Matched component renders here -->
<RouterView />
</template>
Dynamic Routes and Parameters
Dynamic segments in route paths capture values from the URL and make them available as route parameters.
// router/index.js
const routes = [
// Dynamic segment with :id
{ path: "/users/:id", name: "user-detail", component: UserDetail },
// Multiple dynamic segments
{ path: "/posts/:year/:month", component: PostArchive },
// Optional parameter
{ path: "/search/:query?", component: SearchResults },
// Catch-all 404 route
{ path: "/:pathMatch(.*)*", name: "not-found", component: NotFound },
];
<!-- UserDetail.vue -->
<template>
<div>
<h2>User #{{ $route.params.id }}</h2>
<p>Query: {{ $route.query.tab }}</p>
</div>
</template>
<script>
export default {
// Access params via Composition API
// or use props: true in route definition to pass params as props
watch: {
"$route.params.id"(newId) {
this.fetchUser(newId);
},
},
methods: {
fetchUser(id) {
console.log("Fetching user:", id);
},
},
created() {
this.fetchUser(this.$route.params.id);
},
};
</script>
Navigation Guards
Navigation guards let you control access to routes. Global guards protect the entire app, while per-route guards protect specific routes.
// Global guard — runs before every navigation
router.beforeEach((to, from) => {
const isAuthenticated = !!localStorage.getItem("token");
if (to.meta.requiresAuth && !isAuthenticated) {
return { name: "login", query: { redirect: to.fullPath } };
}
});
// Route-level guard
const routes = [
{
path: "/admin",
component: AdminPanel,
meta: { requiresAuth: true, role: "admin" },
beforeEnter: (to, from) => {
const userRole = getUserRole();
if (userRole !== "admin") {
return { name: "unauthorized" };
}
},
},
];
// Programmatic navigation
// this.$router.push("/users/42");
// this.$router.push({ name: "user-detail", params: { id: 42 } });
// this.$router.replace("/login"); // replaces current history entry
// this.$router.go(-1); // go back
Tip: Useprops: truein route definitions to pass route params as component props. This decouples the component from the router, making it easier to test and reuse:{ path: "/users/:id", component: UserDetail, props: true }.
Key Takeaways
- Vue Router maps URL paths to components for single-page application navigation.
- Use
<RouterLink>for navigation and<RouterView>to render matched components. - Dynamic routes with
:paramcapture URL segments as reactive route parameters. - Navigation guards control access to routes for authentication and authorization.
- Lazy-load route components with dynamic imports for better initial load performance.