Vue Router 3

repository·dev·Indexed 12 days ago

https://github.com/vuejs/vue-router

The official router for Vue.js 2 applications (version 3.6.5). It provides a system for mapping components to specific routes, programmatic navigation via the VueRouter instance, and built-in components like <router-link> and <router-view> to handle navigation and rendering in single-page applications.

Tokens
43.8K
Snippets
164
Records
190
Agent score
88%

What's inside Vue Router

  1. Overview of Vue Router features

    dev

    Vue Router is the official router for Vue.js. It is tightly integrated with the Vue.js core to facilitate the creation of Single Page Applications (SPAs).

    Key features include:

    • Nested routes/views mapping: Mapping components to nested URL structures.
    • Modular, component-based configuration: Defining routes using a modular approach.
    • Route parameters, query, and wildcards: Support for dynamic segments, query strings, and catch-all routes.
    • Transition effects: Integration with the Vue.js transition system for route changes.
    • Fine-grained navigation control: Precise control over how users navigate.
    • Automatic active CSS classes: Links automatically receive active classes for styling.
    • HTML5 History mode or Hash mode: Supports modern History API or Hash-based routing (with automatic fallback to Hash mode for IE9).
    • Customizable scroll behavior: Control how the window scrolls during navigation.
  2. Return scroll position descriptors

    dev

    The scrollBehavior function must return a position descriptor. You can use the following formats:

    • Coordinates: { x: number, y: number } (e.g., { x: 0, y: 0 } to scroll to top).
    • Selector: { selector: string, offset?: { x: number, y: number } } to scroll to a specific element. The offset option is supported in version 2.6.0+.
    • Smooth Behavior: Add behavior: 'smooth' to the object to use native smooth scrolling (where supported by the browser).
    // Scroll to top
    scrollBehavior (to, from, savedPosition) {
      return { x: 0, y: 0 }
    }
    
    // Scroll to an anchor/selector
    scrollBehavior (to, from, savedPosition) {
      if (to.hash) {
        return {
          selector: to.hash,
          behavior: 'smooth'
        }
      }
    }
  3. Understand the Route Object and its properties

    dev

    A route object represents the state of the current active route. It is immutable; every successful navigation produces a fresh object. You can access it via this.$route in components, inside navigation guards, or via router.match(location).

    Key Properties:

    • $route.path: Absolute path string (e.g., "/foo/bar").
    • $route.params: Object containing key/value pairs of dynamic segments.
    • $route.query: Object containing key/value pairs of the query string.
    • $route.meta: Object containing custom route meta properties.
    • $route.hash: The hash of the current route (including #).
    • $route.fullPath: The full resolved URL including query and hash.
    • $route.matched: An Array<RouteRecord> containing all route records for nested path segments, from parent to child.
    • $route.name: The name of the current route.
    • $route.redirectedFrom: The name of the route being redirected from.
  4. Use named views to display multiple components simultaneously

    dev

    When you need to display multiple views at the same time without nesting them (for example, a sidebar and a main content area), you can use Named Views.

    Instead of a single outlet, you use multiple <router-view> components. A <router-view> without a name prop is automatically assigned the name default. To use other outlets, provide a name prop to the <router-view> component.

    In your route configuration, you must use the components (plural) option instead of component to map specific components to their corresponding view names.

    <!-- Template usage -->
    <router-view class="view one"></router-view>
    <router-view class="view two" name="a"></router-view>
    <router-view class="view three" name="b"></router-view>
    
    <!-- Route configuration -->
    const router = new VueRouter({
      routes: [
        {
          path: '/',
          components: {
            default: Foo,
            a: Bar,
            b: Baz
          }
        }
      ]
    })
  5. Important: Compatibility and Versioning for vue-router 3.x

    dev

    Version Compatibility Warning

    vue-router 3.x is designed exclusively for Vue 2.0.

    Both Vue 2.0 and vue-router 3.x have reached their end-of-life (EOL). If you are starting a new project or using Vue 3, you should use the appropriate version:

  6. Use Function mode for dynamic or transformed props

    dev

    You can provide a function to the props option. This function receives the route object as an argument and should return an object that will be used as the component's props. This mode is powerful because it allows you to:

    • Cast parameters into different types (e.g., converting a string ID to a number).
    • Combine static values with route-based values.
    • Map query parameters (e.g., route.query) to specific prop names.

    Note: Keep the props function stateless, as it is only evaluated on route changes. If you need to define props based on reactive state, use a wrapper component instead.

    const router = new VueRouter({
      routes: [
        {
          path: '/search',
          component: SearchUser,
          props: route => ({ query: route.query.q })
        }
      ]
    })
    // A URL like /search?q=vue will pass { query: 'vue' } as props to SearchUser
  7. Understand the Full Navigation Resolution Flow

    dev

    When a navigation is triggered, vue-router executes hooks in this specific order:

    1. Call beforeRouteLeave guards in deactivated components.
    2. Call global beforeEach guards.
    3. Call beforeRouteUpdate guards in reused components.
    4. Call beforeEnter in route configs.
    5. Resolve async route components.
    6. Call beforeRouteEnter in activated components.
    7. Call global beforeResolve guards.
    8. Navigation confirmed.
    9. Call global afterEach hooks.
    10. DOM updates triggered.
    11. Call callbacks passed to next in beforeRouteEnter guards with instantiated instances.
  8. How route records and matched routes work

    dev

    A route record is an object within your routes configuration. Since routes can be nested, a single URL (e.g., /foo/bar) can match multiple route records (the parent /foo and the child /bar).

    All route records that match the current URL are exposed in the $route.matched array. When implementing logic that depends on route metadata, you should inspect this array to ensure you account for properties defined on any level of the route hierarchy.

  9. Use `<router-link>` for navigation

    dev

    <router-link> is a component that enables user navigation in a router-supported application. It is preferred over hard-coded <a href="..."> tags because:

    • It works identically in both HTML5 history mode and hash mode, allowing you to switch modes without changing your code.
    • In HTML5 history mode, it prevents the browser from reloading the page by intercepting the click event.
    • In HTML5 history mode, you don't need to include the base option in the to prop URL.

    By default, it renders as an <a> tag with the correct href, but you can customize the rendered tag using the tag prop.

    <router-link to="home">Home</router-link>
  10. Use Function mode for dynamic route props

    dev

    You can provide a function to the props option. This function receives the route object as an argument and should return an object that will be used as the component's props. This allows you to cast parameters to different types or combine route values (like query or params) into a single prop object.

    Note: The props function is only evaluated when the route changes. Do not attempt to store state within this function. If you need to manage state that changes over time, use a wrapper component instead.

    const router = new VueRouter({
      routes: [
        {
          path: '/search',
          component: SearchUser,
          props: (route) => ({ query: route.query.q })
        }
      ]
    })