Vue Router Best Practices
Vue Router Best Practices automation and integration
Category: development Source: antfu/skillsVue Router Best Practices is a community skill for implementing navigation in Vue.js applications, covering route configuration, navigation guards, lazy loading, nested routes, and URL parameter handling for scalable client-side routing.
What Is This?
Overview
Vue Router Best Practices provides guidance on implementing client-side routing effectively in Vue.js applications. It covers route configuration that defines URL patterns with typed parameters, named routes, and alias definitions for clean and maintainable routing tables, navigation guards that implement authentication checks, permission validation, and data prefetching before route transitions complete, lazy loading that splits route components into separate chunks downloaded only when the route is visited for smaller initial bundle sizes, nested routes that organize parent-child layout relationships with shared navigation shells and named views, and URL parameter handling that extracts, validates, and transforms path and query parameters into typed component props. The skill helps developers build well-structured, scalable navigation systems for Vue applications with proper access control and performance optimization.
Who Should Use This
This skill serves Vue developers implementing multi-page application navigation, teams building authenticated route systems with role-based access, and engineers optimizing route-based code splitting.
Why Use It?
Problems It Solves
Route configuration becomes unwieldy without naming conventions and modular organization. Authentication guards need consistent patterns that protect all secured routes without duplication. Loading all route components upfront increases initial bundle size and slows first load. Passing route parameters as untyped strings leads to runtime errors and missing validation.
Core Highlights
Route organizer structures routes with named definitions, aliases, and modular groupings. Guard system implements authentication checks and data prefetching hooks. Lazy loader splits route components into on-demand downloadable chunks. Parameter handler extracts, validates, and types URL values.
How to Use It?
Basic Usage
// router/index.ts
import {
createRouter,
createWebHistory
} from 'vue-router';
const routes = [
{
path: '/',
name: 'home',
component: () => import(
'../views/Home.vue')
},
{
path: '/dashboard',
name: 'dashboard',
component: () => import(
'../views/\
Dashboard.vue'),
meta: {
requiresAuth: true
},
children: [{
path: 'settings',
name: 'settings',
component: () =>
import(
'../views/\
Settings.vue')
}]
}
];
const router = createRouter({
history:
createWebHistory(),
routes
});
export default router;
Real-World Examples
// Navigation guard
import { useAuthStore }
from '@/stores/auth';
router.beforeEach(
(to, from) => {
const auth =
useAuthStore();
if (
to.meta.requiresAuth
&& !auth.isAuth
) {
return {
name: 'login',
query: {
redirect:
to.fullPath
}
};
}
});
// Typed route params
// as props
{
path: '/user/:id',
name: 'user',
component: () => import(
'../views/User.vue'),
props: (route) => ({
id: Number(
route.params.id)
})
}
Advanced Tips
Use route meta fields to declare per-route requirements like authentication, roles, and page titles in a centralized configuration. Pass route parameters as typed props to decouple components from the router API. Group related routes into separate modules and merge them in the main router configuration for better organization.
When to Use It?
Use Cases
Implement authentication-gated routes with redirect-after-login behavior. Set up lazy-loaded routes with loading indicators during chunk downloads. Build a nested dashboard layout with shared sidebar navigation and child views.
Related Topics
Vue Router, Vue.js, navigation guards, code splitting, nested routes, SPA routing, and authentication.
Important Notes
Requirements
Vue 3 with vue-router package installed for client-side routing and navigation management. Vite or webpack for dynamic import support that enables route-level code splitting. Pinia or composable-based state for providing authentication state to navigation guards.
Usage Recommendations
Do: use named routes for programmatic navigation instead of hardcoded path strings. Implement global navigation guards for cross-cutting concerns like authentication. Lazy load all route components except the initial landing page.
Don't: put complex business logic in navigation guards since they should only handle routing decisions. Use route params for data that should persist through navigation since params are lost on page refresh. Forget to handle 404 routes with a catch-all path matcher.
Limitations
Client-side routing requires proper server configuration to redirect all paths to index.html for SPA history mode. Navigation guards run synchronously in sequence which can noticeably delay transitions with multiple async guards. Deep nested routes increase URL complexity and can make breadcrumb generation and route matching logic harder to maintain across the application.