Vue Router 3 Documentation

website·Indexed 19 days ago

https://v3.router.vuejs.org/

Official router for Vue.js, designed to build single-page applications. This documentation covers version 3 for Vue 2, including essentials like dynamic route matching, nested routes, HTML5 history mode, and programmatic navigation, as well as advanced features such as navigation guards, lazy loading, data fetching, and scroll behavior.

Tokens
20.3K
Snippets
127
Records
160
Agent score
87%

What's inside Vue Router 3

  1. Overview of Vue Router features

    Vue Router is the official router for Vue.js, designed to facilitate the creation of Single Page Applications (SPAs) through deep integration with the Vue.js core. Key capabilities include:

    • Nested route and view mapping
    • Modular, component-based router configuration
    • Support for route parameters, queries, and wildcards
    • View transition effects utilizing the Vue.js transition system
    • Fine-grained navigation control
    • Automatic active CSS classes for links
    • Support for both HTML5 history mode and hash mode (with IE9 auto-fallback)
    • Customizable scroll behavior
  2. Overview of Vue Router features

    Vue Router is the official router for Vue.js, designed to facilitate the creation of single-page applications (SPAs) through tight integration with the Vue.js core. Key features include:

    • Nested route/view mapping
    • Modular, component-based router configuration
    • Support for router parameters, queries, and wildcards
    • Transition effects using the Vue.js transition system
    • Fine-grained navigation control
    • Automatic active CSS class application for links
    • Support for HTML5 history mode or hash mode (with automatic fallback for IE9)
    • Customizable scroll behavior
  3. Use <router-link> for user navigation

    <router-link> is the preferred component for navigation in Vue Router apps. It renders as an <a> tag by default and automatically applies an active CSS class when the target route is active. It is superior to hard-coded <a> tags because it handles both HTML5 history and hash modes seamlessly, intercepts click events in history mode to prevent page reloads, and automatically handles the base option in history mode.
    <router-link to="/about">About</router-link>
  4. Render matched components with <router-view>

    <router-view> is a functional component that renders the component matched for the current path. It supports nesting (views within views) and works with <transition> and <keep-alive>. When using both, <keep-alive> must be placed inside <transition>.
    <transition>
      <keep-alive>
        <router-view></router-view>
      </keep-alive>
    </transition>
  5. Use <router-link> for navigation

    <router-link> is a component that enables user navigation in a router-supported app. It is preferred over hard-coded <a> tags because it works consistently across HTML5 history and hash modes, prevents full page reloads in history mode, and automatically handles the base option. By default, it renders as an <a> tag with the correct href.
  6. Access the router and current route in components

    When the router is injected into the root Vue instance, it becomes available in all components via this.$router (the router instance for programmatic navigation) and this.$route (the object containing information about the current active route, such as params).
    export default {
      computed: {
        username () {
          // Access current route parameters
          return this.$route.params.username
        }
      },
      methods: {
        goBack () {
          // Use the router instance for programmatic navigation
          window.history.length > 1
            ? this.$router.go(-1)
            : this.$router.push('/')
        }
      }
    }
  7. Use <router-view> to render route components

    <router-view> is a functional component that renders the component matched by the current route. It can be nested to support nested routes. It works with <transition> and <keep-alive>.
    <transition>
      <keep-alive>
        <router-view></router-view>
      </keep-alive>
    </transition>
  8. Implement a basic Vue Router v3 application

    To create a single-page app with Vue Router, you must map components to routes and specify where they should be rendered. The implementation involves defining route components, creating a routes array, initializing a VueRouter instance, and injecting that instance into the root Vue instance.

    <!-- HTML Setup --> <script src="https://unpkg.com/vue@2/dist/vue.js"></script> <script src="https://unpkg.com/vue-router@3/dist/vue-router.js"></script>

    <div id="app"> <p> <!-- Use router-link for navigation; 'to' prop specifies the destination --> <router-link to="/foo">Go to Foo</router-link> <router-link to="/bar">Go to Bar</router-link> </p> <!-- The component matching the current route is rendered here --> <router-view></router-view> </div>

    <script> // 1. Define route components const Foo = { template: '<div>foo</div>' } const Bar = { template: '<div>bar</div>' }

    // 2. Define routes mapping paths to components const routes = [ { path: '/foo', component: Foo }, { path: '/bar', component: Bar } ]

    // 3. Create router instance const router = new VueRouter({ routes })

    // 4. Create root instance and mount const app = new Vue({ router }).$mount('#app') </script>

  9. Define custom metadata in Vue Router routes

    You can add a meta field to any route definition to store custom data. This is useful for flags like authentication requirements or page titles. Because routes can be nested, a single URL may match multiple route records, each potentially having its own meta object.
    const router = new VueRouter({
      routes: [
        {
          path: '/foo',
          component: Foo,
          children: [
            {
              path: 'bar',
              component: Bar,
              // Custom meta field
              meta: { requiresAuth: true }
            }
          ]
        }
      ]
    })
    
  10. Access route meta fields in navigation guards

    Because routes can be nested, a single URL can match multiple route records. All matched records are available in the matched array on the $route object or the to and from route objects in navigation guards. To check if any matched route record contains a specific meta field, iterate over the matched array using a method like .some().
    router.beforeEach((to, from, next) => {
      // Check if any matched route record has the 'requiresAuth' meta field
      if (to.matched.some(record => record.meta.requiresAuth)) {
        // This route requires auth, check if logged in
        if (!auth.loggedIn()) {
          next({
            path: '/login',
            query: { redirect: to.fullPath }
          })
        } else {
          next()
        }
      } else {
        next() // Always call next() to ensure the navigation hook resolves
      }
    })
    
  11. Fetch data before navigation using beforeRouteEnter

    This approach fetches data before the navigation to the new route is completed. By using the beforeRouteEnter guard, the application can ensure the data is available before the component is rendered. The next callback is called only after the fetch is complete. Because the user remains on the current view during the fetch, it is recommended to show a global progress bar or loading indicator. If the fetch fails, a global error message should be displayed.
    export default {
      data() {
        return {
          post: null,
          error: null
        }
      },
      beforeRouteEnter(to, from, next) {
        getPost(to.params.id, (err, post) => {
          // Call next with a callback to set data on the component instance (vm)
          next(vm => vm.setData(err, post))
        })
      },
      watch: {
        '$route': 'fetchData'
      },
      methods: {
        setData(err, post) {
          this.error = err ? err.toString() : null
          this.post = post
        },
        fetchData() {
          this.error = this.post = null
          this.loading = true
          getPost(this.$route.params.id, (err, post) => {
            this.loading = false
            if (err) {
              this.error = err.toString()
            } else {
              this.post = post
            }
          })
        }
      }
    }
  12. Install Vue Router via npm

    Install the vue-router package using npm. When using a module system, you must explicitly install the router by calling Vue.use(VueRouter). This step is not required when using global script tags.
    npm install vue-router
    import Vue from 'vue'
    import VueRouter from 'vue-router'
    
    Vue.use(VueRouter)