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-simple-routing-cleanup.md

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

Simple Hash Routing Requires Event Listener Cleanup

Impact: MEDIUM - When implementing basic client-side routing without Vue Router (using hash-based routing with hashchange events), you must clean up event listeners when the component unmounts. Failure to do so causes memory leaks and can result in multiple handlers firing after the component is recreated.

Task Checklist

  • Store event listener reference for cleanup
  • Use onUnmounted to remove event listener
  • Consider using Vue Router instead for production apps
  • Test component mount/unmount cycles

The Problem

<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)

// BUG: Event listener is never removed!
// Each time this component mounts, a NEW listener is added
// After mounting 5 times, you have 5 listeners running
window.addEventListener('hashchange', () => {
  currentPath.value = window.location.hash
})

const currentView = computed(() => {
  return routes[currentPath.value.slice(1) || '/']
})
</script>

What happens:

  1. Component mounts, adds listener
  2. Component unmounts (e.g., route change, v-if toggle)
  3. Component mounts again, adds ANOTHER listener
  4. Now TWO listeners respond to each hash change
  5. Eventually causes performance issues and memory leaks

Solution: Proper Cleanup with onUnmounted

<script setup>
import { ref, computed, onUnmounted } from 'vue'
import Home from './Home.vue'
import About from './About.vue'
import NotFound from './NotFound.vue'

const routes = {
  '/': Home,
  '/about': About
}

const currentPath = ref(window.location.hash)

// Store handler reference for cleanup
function handleHashChange() {
  currentPath.value = window.location.hash
}

// Add listener
window.addEventListener('hashchange', handleHashChange)

// CRITICAL: Remove listener on unmount
onUnmounted(() => {
  window.removeEventListener('hashchange', handleHashChange)
})

const currentView = computed(() => {
  return routes[currentPath.value.slice(1) || '/'] || NotFound
})
</script>

Solution: Using Options API

<script>
import Home from './Home.vue'
import About from './About.vue'
import NotFound from './NotFound.vue'

const routes = {
  '/': Home,
  '/about': About
}

export default {
  data() {
    return {
      currentPath: window.location.hash
    }
  },

  computed: {
    currentView() {
      return routes[this.currentPath.slice(1) || '/'] || NotFound
    }
  },

  mounted() {
    // Store bound handler for cleanup
    this.hashHandler = () => {
      this.currentPath = window.location.hash
    }
    window.addEventListener('hashchange', this.hashHandler)
  },

  beforeUnmount() {
    // Clean up
    window.removeEventListener('hashchange', this.hashHandler)
  }
}
</script>

Solution: Composable for Reusable Hash Routing

// composables/useHashRouter.js
import { ref, computed, onUnmounted } from 'vue'

export function useHashRouter(routes, notFoundComponent = null) {
  const currentPath = ref(window.location.hash)

  function handleHashChange() {
    currentPath.value = window.location.hash
  }

  // Setup
  window.addEventListener('hashchange', handleHashChange)

  // Cleanup - handled automatically when component unmounts
  onUnmounted(() => {
    window.removeEventListener('hashchange', handleHashChange)
  })

  const currentView = computed(() => {
    const path = currentPath.value.slice(1) || '/'
    return routes[path] || notFoundComponent
  })

  function navigate(path) {
    window.location.hash = path
  }

  return {
    currentPath,
    currentView,
    navigate
  }
}
<!-- Usage -->
<script setup>
import { useHashRouter } from '@/composables/useHashRouter'
import Home from './Home.vue'
import About from './About.vue'
import NotFound from './NotFound.vue'

const { currentView } = useHashRouter({
  '/': Home,
  '/about': About
}, NotFound)
</script>

<template>
  <component :is="currentView" />
</template>

When to Use Simple Routing vs Vue Router

Use Simple Hash Routing Use Vue Router
Learning/prototyping Production apps
Very simple apps (2-3 pages) Nested routes needed
No build step available Navigation guards needed
Bundle size critical Lazy loading needed
Static hosting only History mode (clean URLs)

Key Points

  1. Always clean up event listeners - Use onUnmounted or beforeUnmount
  2. Store handler reference - Anonymous functions can't be removed
  3. Consider Vue Router for real apps - It handles cleanup automatically
  4. Test unmount scenarios - v-if toggling, hot module replacement
  5. Composables help encapsulate cleanup logic - Reusable and automatic

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.