Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Vue Router 4 reference covering navigation guards, route params, lifecycle interactions, and common gotchas.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
reference/router-use-vue-router-for-production.md
1---2title: Use Vue Router Library for Production Applications3impact: LOW4impactDescription: Simple hash routing lacks essential features for production SPAs; Vue Router provides navigation guards, lazy loading, and proper history management5type: best-practice6tags: [vue3, vue-router, spa, production, architecture]7---89# Use Vue Router Library for Production Applications1011**Impact: LOW** - While you can implement basic routing with hash changes and dynamic components, the official Vue Router library should be used for any production single-page application. It provides essential features like navigation guards, nested routes, lazy loading, and proper browser history integration that are tedious and error-prone to implement manually.1213## Task Checklist1415- [ ] Install Vue Router for production SPAs16- [ ] Use simple routing only for learning or tiny prototypes17- [ ] Leverage built-in features: guards, lazy loading, meta fields18- [ ] Consider router-based state and data loading patterns1920## When Simple Routing is Acceptable2122```vue23<!-- Only for: learning, prototypes, or micro-apps with 2-3 pages -->24<script setup>25import { ref, computed } from 'vue'26import Home from './Home.vue'27import About from './About.vue'2829const routes = { '/': Home, '/about': About }30const currentPath = ref(window.location.hash.slice(1) || '/')3132window.addEventListener('hashchange', () => {33currentPath.value = window.location.hash.slice(1) || '/'34})3536const currentView = computed(() => routes[currentPath.value])37</script>3839<template>40<nav>41<a href="#/">Home</a>42<a href="#/about">About</a>43</nav>44<component :is="currentView" />45</template>46```4748## Why Vue Router for Production4950### Features You'd Have to Implement Manually5152| Feature | Simple Routing | Vue Router |53|---------|---------------|------------|54| Navigation guards | Manual, error-prone | Built-in, composable |55| Nested routes | Complex to implement | Native support |56| Route params | Parse manually | Automatic extraction |57| Lazy loading | DIY with dynamic imports | Built-in with code splitting |58| History mode (clean URLs) | Requires server config + manual | Built-in |59| Scroll behavior | Manual | Configurable |60| Route transitions | DIY | Integrated with Transition |61| Active link styling | Manual class toggling | `router-link-active` class |62| Programmatic navigation | `location.hash = ...` | `router.push()`, `router.replace()` |63| Route meta fields | N/A | Built-in |6465## Production Setup with Vue Router6667```javascript68// router/index.js69import { createRouter, createWebHistory } from 'vue-router'7071const routes = [72{73path: '/',74name: 'Home',75component: () => import('@/views/Home.vue'), // Lazy loaded76meta: { requiresAuth: false }77},78{79path: '/dashboard',80name: 'Dashboard',81component: () => import('@/views/Dashboard.vue'),82meta: { requiresAuth: true },83children: [84{85path: 'settings',86name: 'Settings',87component: () => import('@/views/Settings.vue')88}89]90},91{92path: '/users/:id',93name: 'UserProfile',94component: () => import('@/views/UserProfile.vue'),95props: true // Pass params as props96},97{98path: '/:pathMatch(.*)*',99name: 'NotFound',100component: () => import('@/views/NotFound.vue')101}102]103104const router = createRouter({105history: createWebHistory(),106routes,107scrollBehavior(to, from, savedPosition) {108return savedPosition || { top: 0 }109}110})111112// Global navigation guard113router.beforeEach((to, from) => {114if (to.meta.requiresAuth && !isAuthenticated()) {115return { name: 'Login', query: { redirect: to.fullPath } }116}117})118119export default router120```121122```javascript123// main.js124import { createApp } from 'vue'125import App from './App.vue'126import router from './router'127128createApp(App)129.use(router)130.mount('#app')131```132133```vue134<!-- App.vue -->135<template>136<nav>137<router-link to="/">Home</router-link>138<router-link to="/dashboard">Dashboard</router-link>139</nav>140141<router-view v-slot="{ Component }">142<transition name="fade" mode="out-in">143<component :is="Component" />144</transition>145</router-view>146</template>147```148149## Modern Vue Router Features (2025+)150151```javascript152// Data Loading API (Vue Router 4.2+)153const routes = [154{155path: '/users/:id',156component: UserProfile,157// Load data at route level158loader: async (route) => {159return { user: await fetchUser(route.params.id) }160}161}162]163164// View Transitions API integration165const router = createRouter({166// Enable native browser view transitions167// Requires browser support (Chrome 111+)168})169```170171## Key Points1721731. **Use Vue Router for any app beyond a prototype** - The features are essential1742. **Simple routing is for learning** - Understand the concepts, then use the library1753. **Lazy loading is critical for bundle size** - Vue Router makes it trivial1764. **Navigation guards prevent security issues** - Hard to get right manually1775. **History mode requires Vue Router** - Clean URLs need proper handling1786. **New features keep coming** - Data Loading API, View Transitions179180## Reference181- [Vue.js Routing Guide](https://vuejs.org/guide/scaling-up/routing.html)182- [Vue Router Documentation](https://router.vuejs.org/)183- [Vue Router Getting Started](https://router.vuejs.org/guide/)184