All skills
hyf0 avatar

/vue-router-best-practices

@bc922e4 official
by hyf0hyf0/vue-skills2.9k stars
167

Vue Router 4 patterns, navigation guards, route params, and route-component lifecycle interactions.

Use this Skill: https://skilld.dev/gh/hyf0/vue-skills/vue-router-best-practices

This session only. Nothing lands on disk.

referencerouter-use-vue-router-for-production.md

≈1.3k tokens on demand. Your agent reads this file only when SKILL.md points to it.

Use Vue Router Library for Production Applications

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.

Task Checklist

  • Install Vue Router for production SPAs
  • Use simple routing only for learning or tiny prototypes
  • Leverage built-in features: guards, lazy loading, meta fields
  • Consider router-based state and data loading patterns

When Simple Routing is Acceptable

<!-- Only for: learning, prototypes, or micro-apps with 2-3 pages -->
<script setup>
import { ref, computed } from 'vue'
import Home from './Home.vue'
import About from './About.vue'

const routes = { '/': Home, '/about': About }
const currentPath = ref(window.location.hash.slice(1) || '/')

window.addEventListener('hashchange', () => {
  currentPath.value = window.location.hash.slice(1) || '/'
})

const currentView = computed(() => routes[currentPath.value])
</script>

<template>
  <nav>
    <a href="#/">Home</a>
    <a href="#/about">About</a>
  </nav>
  <component :is="currentView" />
</template>

Why Vue Router for Production

Features You'd Have to Implement Manually

Feature Simple Routing Vue Router
Navigation guards Manual, error-prone Built-in, composable
Nested routes Complex to implement Native support
Route params Parse manually Automatic extraction
Lazy loading DIY with dynamic imports Built-in with code splitting
History mode (clean URLs) Requires server config + manual Built-in
Scroll behavior Manual Configurable
Route transitions DIY Integrated with Transition
Active link styling Manual class toggling router-link-active class
Programmatic navigation location.hash = ... router.push(), router.replace()
Route meta fields N/A Built-in

Production Setup with Vue Router

// router/index.js
import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('@/views/Home.vue'),  // Lazy loaded
    meta: { requiresAuth: false }
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('@/views/Dashboard.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: 'settings',
        name: 'Settings',
        component: () => import('@/views/Settings.vue')
      }
    ]
  },
  {
    path: '/users/:id',
    name: 'UserProfile',
    component: () => import('@/views/UserProfile.vue'),
    props: true  // Pass params as props
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/NotFound.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    return savedPosition || { top: 0 }
  }
})

// Global navigation guard
router.beforeEach((to, from) => {
  if (to.meta.requiresAuth && !isAuthenticated()) {
    return { name: 'Login', query: { redirect: to.fullPath } }
  }
})

export default router
// main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

createApp(App)
  .use(router)
  .mount('#app')
<!-- App.vue -->
<template>
  <nav>
    <router-link to="/">Home</router-link>
    <router-link to="/dashboard">Dashboard</router-link>
  </nav>

  <router-view v-slot="{ Component }">
    <transition name="fade" mode="out-in">
      <component :is="Component" />
    </transition>
  </router-view>
</template>

Modern Vue Router Features (2025+)

// Data Loading API (Vue Router 4.2+)
const routes = [
  {
    path: '/users/:id',
    component: UserProfile,
    // Load data at route level
    loader: async (route) => {
      return { user: await fetchUser(route.params.id) }
    }
  }
]

// View Transitions API integration
const router = createRouter({
  // Enable native browser view transitions
  // Requires browser support (Chrome 111+)
})

Key Points

  1. Use Vue Router for any app beyond a prototype - The features are essential
  2. Simple routing is for learning - Understand the concepts, then use the library
  3. Lazy loading is critical for bundle size - Vue Router makes it trivial
  4. Navigation guards prevent security issues - Hard to get right manually
  5. History mode requires Vue Router - Clean URLs need proper handling
  6. New features keep coming - Data Loading API, View Transitions

Reference

Source: SKILL.md on GitHub

No alerts16d5 checks · Risk SAFE
  • Gen Agent Trust Hub16d

    This skill is a collection of educational documentation and best practices for using Vue Router 4. It contains no executable code, network operations, or sensitive data access, and is focused entirely on providing guidance for frontend development patterns.

  • Socket16d

    No alerts

  • Snyk16d

    Risk: LOW · No issues

  • Runlayer7mo

    9 files scanned · No issues

  • ZeroLeaks5mo

    Score: 93/100 · 2 sections analyzed

Signed by skilld at bc922e4. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 2 months ago.

Steadyupdated 8 months ago
version
1.0.0
author
github.com/vuejs-ai

README badge

README badge for hyf0/vue-skills/vue-router-best-practices

Teaches Vue Router 4 navigation guards, route lifecycle patterns, and common gotchas like stale data when params change and infinite redirect loops. Covers async/await in guards, beforeRouteEnter access patterns, and cleanup on component unmount.

Generated from the current SKILL.md.

Does this cover Vue Router 3 or Vue Router 4?
This skill targets Vue Router 4 specifically. It covers patterns and navigation guards in Vue 4's composition API context.
What are the main topics covered?
Navigation guards (beforeRouteEnter, beforeEach, infinite loops, async patterns), route lifecycle gotchas (stale data, cleanup), and production single-page app setup.
Does this address the deprecated next() function?
Yes. The skill includes guidance on replacing deprecated next() callbacks with modern return-based patterns in Vue Router 4.
Will this help with same-route navigation issues?
Yes. It covers both navigating to the same route with different params and stale data problems when component lifecycle hooks don't trigger on param changes.

Generated from the current SKILL.md. These answers refresh after source changes.