SoFunction
Updated on 2025-04-13

Core technology of parameter delivery and navigation guarding in Vue3 routing advanced practical tutorial

1. Advanced application skills for routing parameter transfer

1.1 Routing configuration and parameter verification

// router/
{
  path: '/user/:userId(\\d+)', // Use regular expression restrictions to match only numbers  name: 'UserDetail',
  component: () => import('../views/'),
  props: true // Enable props parameter transfer mode}

Technical points:

  • Improve parameter security by constraining the parameter format with regular expressions (such as\\d+Limit to numbers)
  • Use lazy routing to improve performance
  • Enable props mode to achieve component decoupling

1.2 Three ways to receive component parameters

<!--  -->
<script setup>
// Method 1: Get it through useRouteconst route = useRoute()
()
// Method 2: Receive through props (recommended)const props = defineProps({
  userId: {
    type: [String, Number],
    required: true
  }
})
// Method 3: Change of watch parameterswatch(() => , (newVal) => {
  // Handle parameter change logic})
</script>

2. Query parameters: realize complex data transmission

2.1 Query parameter delivery skills

usequeryObjects are passed non-sensitive data, and object nesting is supported:

// Programming navigation({
  path: '/search',
  query: {
    keywords: 'vue3',
    filters: {
      sort: 'latest',
      page: 2
    }
  }
});

2.2 Parameter serialization and deserialization

Automatic conversion of complex objects is achieved through routing configuration:

//Routing configuration{
  path: '/search',
  name: 'Search',
  component: SearchView,
  props: (route) => ({
    keywords: ,
    filters: ()
  })
}

Note: URLs will automatically encode URI, special character processing should be paid attention to

2.3 Best practices for safe parameter transfer

// Use encodeURIComponent to handle special charactersconst searchParams = {
  q: encodeURIComponent('vue3+router'),
  page: 1
}
({ path: '/search', query: searchParams })

2.4 Type conversion and default value processing

// Handle numerical parametersconst page = Number() || 1
const minPrice = parseFloat() ?? 0
// Date parameter processingconst startDate =  
  ? new Date()
  : new Date()

3. Navigation Guard: Building a Secure Routing System

3.1 Analysis of the entire process of guard execution

Guard Type Execution timing Use scenarios
beforeEach Global front guard Permission verification, login status check
beforeResolve Global Analysis Guard Data preload
afterEach Global back hook Page access statistics
beforeEnter Route exclusive guard Specific routing permission control
Guarding inside components When component creation/update/destroy Data storage, departure confirmation

3.2 Global front guard (multi-level permission control system)

// Global Front Guard Advanced Edition(async (to, from) => {
  const requiresAuth = (record => )
  const userStore = useUserStore()
  // Logged in user access login page redirection  if ( === 'Login' && ) {
    return { name: 'Home' }
  }
  // Routing processing that requires authentication  if (requiresAuth && !) {
     = 
    return { name: 'Login' }
  }
  // Dynamic permission verification  if () {
    const hasPermission = await checkPermissions()
    if (!hasPermission) return { name: 'Forbidden' }
  }
})

3.3 Route exclusive guard

{
  path: '/dashboard',
  component: Dashboard,
  beforeEnter: (to) => {
    const requiredRole = ;
    const userRole = useAuthStore().;
    if (requiredRole && !(userRole)) {
      return '/403';
    }
  }
}

3.4 Practical skills of component guarding

<script setup>
// Asynchronous processing of leaving the guardonBeforeRouteLeave(async (to, from, next) => {
  if () {
    try {
      await saveDraft()
      next()
    } catch (error) {
      next(false)
      showError('Auto-save failed, please save manually')
    }
  } else {
    next()
  }
})
// Parameter change processingonBeforeRouteUpdate(async (to) => {
  await loadUserData()
  (0, 0)
})
</script>

4. Performance optimization and best practices

4.1 Lazy loading of routes

Improve the loading speed of the first screen through dynamic import:

const routes = [
  {
    path: '/about',
    component: () => import('../views/')
  }
];

4.2 Routing meta information

Use meta fields to implement extended functions:

{
  path: '/admin',
  component: AdminPanel,
  meta: {
    requiresAuth: true,
    role: ['admin', 'superuser'],
    keepAlive: true  // Control page cache  }
}

4.3 Error handling scheme

Unified handling of routing exceptions:

((error, to) => {
  if (('Failed to fetch')) {
    ({ name: 'NetworkError', query: { path:  } });
  }
});

5. Frequently Asked Questions

5.1 Troubleshooting of parameter loss

  • Scene: Parameters are lost after page refresh
  • Solution

    uselocalStorageTemporary storage of key parameters

    Configure the server to support History mode

    usebeforeEachGuard Verify Parameter Validity

5.2 Handling navigation loop problem

// Add a termination condition in the global guard((to, from) => {
  if ( === 'Login' &&  === 'Login') {
    return false // Terminate the navigation loop  }
})

This is the article about the core technology of parameter delivery and navigation guards in Vue3 routing advanced practical tutorial. For more related Vue3 parameter delivery and navigation guards, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!