All skills
vuejs-ai avatar

/vue-router-best-practices

@bc922e4 official
by Vue AIvuejs-ai/skills2.9k stars
167

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

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

This session only. Nothing lands on disk.

referencerouter-param-change-no-lifecycle.md

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

Route Param Changes Do Not Trigger Lifecycle Hooks

Impact: HIGH - When navigating between routes that use the same component (e.g., /users/1 to /users/2), Vue Router reuses the existing component instance for performance. This means onMounted, created, and other lifecycle hooks do NOT fire, leaving you with stale data from the previous route.

Task Checklist

  • Use watch on route params for data fetching
  • Or use onBeforeRouteUpdate in-component guard
  • Or use :key="route.params.id" to force re-creation (less efficient)
  • Never rely solely on onMounted for route-param-dependent data

The Problem

<!-- UserProfile.vue - Used for /users/:id -->
<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'

const route = useRoute()
const user = ref(null)

// BUG: Only runs once when component first mounts!
// Navigating from /users/1 to /users/2 does NOT trigger this
onMounted(async () => {
  user.value = await fetchUser(route.params.id)
})
</script>

<template>
  <div>
    <!-- Still shows User 1 data when navigating to /users/2! -->
    <h1>{{ user?.name }}</h1>
  </div>
</template>

Scenario:

  1. Visit /users/1 - Component mounts, fetches User 1 data
  2. Navigate to /users/2 - Component is REUSED, onMounted doesn't run
  3. UI still shows User 1's data!

Solution 1: Watch Route Params (Recommended)

<script setup>
import { ref, watch } from 'vue'
import { useRoute } from 'vue-router'

const route = useRoute()
const user = ref(null)
const loading = ref(false)

// Watch for param changes - handles both initial load and navigation
watch(
  () => route.params.id,
  async (newId) => {
    loading.value = true
    user.value = await fetchUser(newId)
    loading.value = false
  },
  { immediate: true }  // Run immediately for initial load
)
</script>

Solution 2: Use onBeforeRouteUpdate Guard

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, onBeforeRouteUpdate } from 'vue-router'

const route = useRoute()
const user = ref(null)

async function loadUser(id) {
  user.value = await fetchUser(id)
}

// Initial load
onMounted(() => loadUser(route.params.id))

// Handle param changes within same route
onBeforeRouteUpdate(async (to, from) => {
  if (to.params.id !== from.params.id) {
    await loadUser(to.params.id)
  }
})
</script>

Solution 3: Force Component Re-creation with Key

<!-- App.vue or parent component -->
<template>
  <router-view :key="$route.fullPath" />
</template>

Tradeoffs:

  • Simple but less performant
  • Destroys and recreates component on every param change
  • Loses component state
  • Use only when component state should reset completely

Solution 4: Composable for Route-Reactive Data

// composables/useRouteData.js
import { ref, watch } from 'vue'
import { useRoute } from 'vue-router'

export function useRouteData(paramName, fetcher) {
  const route = useRoute()
  const data = ref(null)
  const loading = ref(false)
  const error = ref(null)

  watch(
    () => route.params[paramName],
    async (id) => {
      if (!id) return

      loading.value = true
      error.value = null

      try {
        data.value = await fetcher(id)
      } catch (e) {
        error.value = e
      } finally {
        loading.value = false
      }
    },
    { immediate: true }
  )

  return { data, loading, error }
}
<!-- Usage in component -->
<script setup>
import { useRouteData } from '@/composables/useRouteData'
import { fetchUser } from '@/api/users'

const { data: user, loading, error } = useRouteData('id', fetchUser)
</script>

What Triggers vs. What Doesn't

Navigation Type Lifecycle Hooks beforeRouteUpdate Watch on params
/users/1 to /posts/1 YES NO YES
/users/1 to /users/2 NO YES YES
/users/1?tab=a to /users/1?tab=b NO YES NO (different watch)
/users/1 to /users/1 (same) NO NO NO

Key Points

  1. Same route, different params = same component instance - This is a performance optimization
  2. Lifecycle hooks only fire once - When component first mounts
  3. Use watch with immediate: true - Covers both initial load and updates
  4. onBeforeRouteUpdate is navigation-aware - Good for data that must load before view updates
  5. :key="route.fullPath" is a sledgehammer - Use only when necessary

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
  • Vue
  • vue-router
  • navigation-guards
  • routing
  • lifecycle
  • spa

README badge

README badge for vuejs-ai/skills/vue-router-best-practices

Teaches Vue Router 4 navigation guards, route lifecycle handling, and common patterns like preventing infinite redirects and managing stale data across param changes. Covers gotchas like component cleanup on navigation and the deprecated next() function.

Generated from the current SKILL.md.

Does this skill cover Vue Router 4?
Yes. The skill is specific to Vue Router 4 patterns, navigation guards, route params, and component lifecycle interactions.
What are the main topics covered?
Navigation guards (async/await, infinite loops, deprecated next() function), route lifecycle issues (stale data, cleanup), and production SPA setup.
Does this address the problem of component data not updating when route params change?
Yes. The skill includes guidance on handling stale data when navigating between the same route with different params.
Does this cover how to access component instances in navigation guards?
Yes. It addresses the gotcha that `this` is not available in beforeRouteEnter guards and explains the workaround.
Does this skill help prevent infinite redirect loops?
Yes. It includes patterns for identifying and avoiding infinite navigation guard redirect loops.

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