Vue Router Documentation

website·Indexed 33 days ago

https://router.vuejs.kr

Official documentation for Vue Router, the official router for Vue.js. Covers essential routing concepts, advanced features like navigation guards and lazy loading, and migration guides from v3 to v4 and v4 to v5. Includes detailed sections on file-based routing, data loaders using defineLoader(), and integration with the Composition API and Nuxt.

Tokens
31.3K
Snippets
183
Records
221
Agent score
64%

What's inside Vue Router

  1. Overview of Vue Router Data Loaders

    Data Loaders simplify asynchronous state management (like data fetching) in Vue Router by moving loading logic outside of the component setup function. This ensures that data is collected and awaited within navigation guards, guaranteeing that data is ready before the component renders. Key features include parallel data fetching, deduplication, automatic loading state management, error handling, SSR support, and data prefetching.
  2. Overview of Vue Router capabilities

    Vue Router is the official router for Vue.js, deeply integrated with the Vue.js core to facilitate the creation of single-page applications (SPAs). Its primary features include:

    • Nested route mapping
    • Dynamic routing
    • Modular, component-based router configuration
    • Support for route params, queries, and wildcards
    • View transitions powered by the Vue.js transition system
    • Fine-grained navigation control
    • Automatic active CSS class application for links
    • Support for HTML5 history mode or hash mode
    • Customizable scroll behavior
    • Proper URL encoding
  3. Understand file-based routing folder structure

    The plugin automatically generates a routing structure based on .vue files located in the src/pages folder. This eliminates the need to manually maintain a routes array. Files and folders map directly to URL paths.
    src/pages/
    ├── index.vue       -> /
    ├── about.vue       -> /about
    └── users/
        ├── index.vue   -> /users
        └── [id].vue    -> /users/:id
  4. Configure ESLint for vue-router auto-routes without auto-imports

    If you are not using auto-imports, you must inform ESLint about vue-router/auto-routes to prevent import errors. Add the module to the import/core-modules setting in your ESLint configuration.
    {
      "settings": {
        "import/core-modules": ["vue-router/auto-routes"]
      }
    }
  5. Understand default error behavior in Data Loaders

    By default, any error thrown in a loader is treated as an 'unexpected error'. This behavior halts navigation, similar to navigation guards, and the error is intercepted by router.onError(). Consequently, the error will not appear in the loader's error property. However, for non-navigation-aware loaders (such as lazy loaders or data reloading), errors cannot be intercepted by Vue Router and will be maintained in the loader's error property.
  6. Add nested routes dynamically

    To add a child route to an existing parent route, pass the parent route's name as the first argument to router.addRoute(). The second argument is the route record for the child.
    // First, ensure the parent route exists
    router.addRoute({ name: 'admin', path: '/admin', component: Admin })
    
    // Add a child route to the 'admin' parent
    router.addRoute('admin', { path: 'settings', component: AdminSettings })
  7. Create a Catch-all or 404 Not Found route

    Standard params only match characters between / separators. To match any path (including those with slashes), use a custom parameter with a regular expression in parentheses. To create a 404 page, use a parameter with (.*)* to make it match everything and mark it as optional/repeatable.
    const routes = [
      // Matches everything and puts it into route.params.pathMatch
      { path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound },
      
      // Matches any path starting with '/user-' and puts the rest in route.params.afterUser
      { path: '/user-:afterUser(.*)', component: UserGeneric },
    ]
  8. Define a basic data loader using defineBasicLoader

    Data loaders are composables created using defineLoader functions (such as defineBasicLoader or defineColadaLoader). A loader is defined by providing a route pattern and an asynchronous function that fetches the required data. The resulting composable provides reactive state including data, isLoading, error, and a reload function.
    <script lang="ts">
    import 'vue-router/auto-routes'
    import { defineBasicLoader } from 'vue-router/experimental'
    import { getUserById } from '../api'
    
    export const useUserData = defineBasicLoader('/users/[id]', async to => {
      return getUserById(to.params.id)
    })
    </script>
    
    <script setup lang="ts">
    const {
      data: user, // Data returned by the loader
      isLoading, // Boolean indicating if data is being fetched
      error,      // Error object if the loader failed
      reload,     // Function to refetch data without navigation
    } = useUserData()
    </script>
  9. Attach arbitrary data to routes using the meta field

    The meta property allows you to attach custom information to a route record, such as transition names or access control roles. This data is accessible within the route location and navigation guards.
    const routes = [
      {
        path: '/posts',
        component: PostsLayout,
        children: [
          {
            path: 'new',
            component: PostsNew,
            // Only authenticated users can create posts
            meta: { requiresAuth: true },
          },
          {
            path: ':id',
            component: PostsDetail,
            // Anyone can read posts
            meta: { requiresAuth: false },
          },
        ],
      },
    ]
  10. Set up file-based routing from scratch

    1. Create a src/pages folder and add an index.vue component (this serves as the root / route).
    2. Import routes from vue-router/auto-routes and provide it to the createRouter configuration.
    import { createApp } from 'vue'
    import { createRouter, createWebHistory } from 'vue-router'
    import { routes } from 'vue-router/auto-routes'
    import App from './App.vue'
    
    const router = createRouter({
      history: createWebHistory(),
      routes,
    })
    
    createApp(App).use(router).mount('#app')
  11. Detect and handle navigation failures

    When a navigation is blocked (e.g., by a guard returning false or if the user is already on the target page), router.push resolves with a Navigation Failure object. If the navigation is successful (including redirects), it resolves with a falsy value (usually undefined). Use the isNavigationFailure utility and NavigationFailureType enum to identify the specific reason for the failure.
    import { NavigationFailureType, isNavigationFailure } from 'vue-router'
    
    const navigationResult = await router.push('/articles/2')
    
    if (navigationResult) {
      // Navigation was prevented
      if (isNavigationFailure(navigationResult, NavigationFailureType.aborted)) {
        showToast('You have unsaved changes, discard and leave anyway?')
      }
    } else {
      // Navigation succeeded (including redirects)
      this.isMenuOpen = false
    }
  12. Implement non-blocking data fetching with Lazy Loaders

    Set lazy: true in the defineLoader options to create a lazy loader. Lazy loaders do not block navigation; the navigation completes immediately, and the data property of the returned composable will initially be undefined. Errors thrown in lazy loaders do not block navigation and are always captured in the error property.
    import { defineBasicLoader as defineLoader } from 'vue-router/experimental'
    import { getUserById } from '../api'
    
    export const useUserData = defineLoader(
      '/users/[id]',
      async (route) => {
        const user = await getUserById(route.params.id)
        return user
      },
      { lazy: true } // Navigation is not blocked
    )