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-beforerouteenter-no-this.md

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

beforeRouteEnter Cannot Access Component Instance

Impact: MEDIUM - The beforeRouteEnter in-component navigation guard executes BEFORE the component is created, meaning you cannot access this or any component instance properties. This is the ONLY navigation guard that supports a callback in the next() function to access the component instance after navigation.

Task Checklist

  • Use next(vm => ...) callback to access component instance
  • Or use composition API guards which have different patterns
  • Move data fetching logic appropriately based on timing needs
  • Consider using global guards for data that doesn't need component access

The Problem

// Options API - WRONG: this is undefined
export default {
  data() {
    return { user: null }
  },
  beforeRouteEnter(to, from, next) {
    // BUG: this is undefined here - component doesn't exist yet!
    this.user = await fetchUser(to.params.id)  // ERROR!
    next()
  }
}

Solution: Use next() Callback (Options API)

// Options API - CORRECT: Use callback to access vm
export default {
  data() {
    return {
      user: null,
      loading: true
    }
  },

  beforeRouteEnter(to, from, next) {
    // Fetch data before component exists
    fetchUser(to.params.id)
      .then(user => {
        // Pass callback to next() - receives component instance as 'vm'
        next(vm => {
          vm.user = user
          vm.loading = false
        })
      })
      .catch(error => {
        next(vm => {
          vm.error = error
          vm.loading = false
        })
      })
  }
}

Solution: Async beforeRouteEnter (Options API)

export default {
  data() {
    return { userData: null }
  },

  async beforeRouteEnter(to, from, next) {
    try {
      const user = await fetchUser(to.params.id)

      // Still need callback for component access
      next(vm => {
        vm.userData = user
      })
    } catch (error) {
      // Redirect on error
      next('/error')
    }
  }
}

Composition API Alternative

In Composition API with <script setup>, you cannot use beforeRouteEnter directly because the component instance is being set up. Use different patterns instead:

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

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

// Option 1: Fetch in onMounted (after component exists)
onMounted(async () => {
  user.value = await fetchUser(route.params.id)
  loading.value = false
})

// Option 2: Handle subsequent param changes
onBeforeRouteUpdate(async (to, from) => {
  if (to.params.id !== from.params.id) {
    loading.value = true
    user.value = await fetchUser(to.params.id)
    loading.value = false
  }
})
</script>

Route-Level Data Fetching

For data that should load BEFORE navigation, use route-level guards:

// router.js
const routes = [
  {
    path: '/users/:id',
    component: () => import('./UserProfile.vue'),
    beforeEnter: async (to, from) => {
      try {
        // Store data for component to access
        const user = await fetchUser(to.params.id)
        to.meta.user = user  // Attach to route meta
      } catch (error) {
        return '/error'
      }
    }
  }
]
<!-- UserProfile.vue -->
<script setup>
import { useRoute } from 'vue-router'

const route = useRoute()
// Access pre-fetched data from meta
const user = route.meta.user
</script>

Comparison of Navigation Guards

Guard Has this/component? Can delay navigation? Use case
beforeRouteEnter NO (use next callback) YES Pre-fetch, redirect if data missing
beforeRouteUpdate YES YES React to param changes
beforeRouteLeave YES YES Unsaved changes warning
Global beforeEach NO YES Auth checks
Route beforeEnter NO YES Route-specific validation

Key Points

  1. beforeRouteEnter runs before component creation - No access to this
  2. Use next(vm => ...) callback - Only way to access component instance
  3. Composition API has limitations - Use onMounted or global guards instead
  4. Consider route meta for pre-fetched data - Clean separation of concerns
  5. beforeRouteUpdate and beforeRouteLeave have component access - They run when component exists

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.