Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 87 ยท Routing and Navigation

Vue Router Advanced Features

Go beyond the basics with Vue Router - nested routes, meta fields, navigation guards, lazy-loaded routes and scroll behavior, with runnable stand-ins for nesting and guards.

Small apps need a route table and two components. Real apps need more: a settings area with its own sub-navigation, pages that only signed-in users can open, code that loads only when someone visits a page, and a sensible scroll position after navigation. Vue Router has a feature for each, and they all build on the basics from Vue Router Basics.

As before, the live editor cannot install the real library, so the library code appears as read-only snippets and the two runnable examples use small stand-ins with the same API shape. The route tables, guards and meta fields in them are exactly what you would write in a real project.

Nested routes

Many screens are built from a stable layout and an area that changes: a settings page with a side menu, a dashboard with tabs, a shop with a product panel. Nested routes model that. A route record gets a children array, and its component contains its own <RouterView> where the active child appears.

JavaScript
const routes = [
  {
    path: "/settings",
    component: SettingsLayout,
    children: [
      { path: "", component: SettingsHome },          // /settings
      { path: "profile", component: ProfileView },    // /settings/profile
      { path: "billing", component: BillingView }     // /settings/billing
    ]
  }
];

Three details to remember:

  • Child paths without a leading slash are appended to the parent's path. A child path starting with / is treated as a root path and breaks the nesting.
  • A child with path: "" is the default child: it renders when the URL is exactly the parent's path. Without it, /settings would show the layout with an empty area.
  • A URL matches a chain of records: parent first, then child. Each <RouterView> renders the record at its own depth. The first (outermost) one renders the layout, and the one inside the layout renders the child.
flowchart TD
  A["App.vue<br/>RouterView depth 0"] --> B["SettingsLayout<br/>(matched[0])"]
  B --> C["RouterView depth 1"]
  C --> D["ProfileView<br/>(matched[1])"]
  E["URL: /settings/profile"] -.-> F["route.matched = [settings, profile]"]

A nested URL matches a chain of records; each RouterView renders the record at its own depth.

That chain is available as route.matched, which is handy for breadcrumbs. Try the stand-in below: click around, watch the breadcrumb and the matched count, and notice that the "Settings" heading and its sub-navigation never re-render while the child area changes.

Nested routes, depth-aware RouterView and meta breadcrumbs

Click Settings: the breadcrumb is Settings and 2 records matched (the layout and its empty-path default child). Click Profile: Settings / Profile, still 2 records. The breadcrumb comes straight from meta.title on each matched record, which brings us to the next feature.

Meta fields

A route record can carry arbitrary data in its meta object. The router never interprets it; it simply makes it available on route.meta and on every entry in route.matched. Typical uses are page titles, breadcrumb labels, layout names and permission flags:

JavaScript
{ path: "/account", component: AccountView, meta: { requiresAuth: true, title: "My account" } }

For nested routes, route.meta is the merge of every matched record's meta, with the child winning. That is useful for flags like requiresAuth set once on a parent: every child inherits it.

A guard is a function the router calls during a navigation. It can allow it, cancel it or redirect somewhere else. Guards are how you protect pages, confirm unsaved changes and run logic that must happen on every navigation.

The most common one is the global beforeEach:

JavaScript
router.beforeEach((to, from) => {
  if (to.meta.requiresAuth && !auth.user) {
    return { path: "/login", query: { redirect: to.fullPath } };
  }
});

What the guard returns decides the outcome:

Return value Effect
nothing, undefined or true The navigation continues
false The navigation is cancelled and the URL stays where it was
a route location (a string or an object) The navigation is redirected there
throws an error The navigation fails and error handlers run

Guards can also be async: return a promise, and the navigation waits for it. Keep them quick, because the user is staring at the old page while guards run. Fetch big data in the page, not in a guard.

There are three places to attach guards:

  • Global: router.beforeEach, router.beforeResolve and router.afterEach. The last one cannot cancel anything; it is for analytics and updating document.title.
  • Per route: a beforeEnter function on one record.
  • In components: onBeforeRouteLeave (warn about unsaved changes) and onBeforeRouteUpdate (the same component is reused for new params), imported from vue-router inside <script setup>.
flowchart TD
  A["Navigation starts"] --> B["onBeforeRouteLeave<br/>in leaving components"]
  B --> C["Global beforeEach"]
  C --> D["onBeforeRouteUpdate<br/>in reused components"]
  D --> E["beforeEnter<br/>in the route record"]
  E --> F["Resolve lazy components"]
  F --> G["Global beforeResolve"]
  G --> H["Navigation confirmed"]
  H --> I["Global afterEach<br/>then DOM updates"]

Any guard in the chain can cancel or redirect; if none does, the navigation is confirmed and afterEach runs.

A guard you can run

The stand-in below implements beforeEach with the same return values. It has a login page, an account page that needs a sign-in (meta.requiresAuth) and an admin page that needs more (meta.requiresAdmin). Every decision the guard makes is written to the log at the bottom.

beforeEach guards, redirects and meta flags

Work through three scenarios:

  1. Signed out, click Account. The guard sees requiresAuth and no user, so it returns a redirect object. You land on /login with a redirect query holding the original target.
  2. Click Sign in as Ada (user). The login page pushes to route.query.redirect, so you arrive at the Account page you originally wanted. This "remember where they were going" pattern is the standard login flow.
  3. Click Admin as Ada. The guard returns false: the navigation is cancelled and the URL and the page stay as they were. Sign in as Root and the same link works.

A guard protects the screen, not the data. Anyone can open DevTools and call your API directly, or read JavaScript that is already in the bundle. The server must check permissions on every request. Treat guards as user-experience, not security. See Authentication Patterns and Security in Vue.

Lazy-loaded routes

By default, every page component is imported at the top of the router file, so the whole app downloads before the first screen appears. A lazy route uses a dynamic import() instead. Bundlers such as Vite split each one into a separate file that downloads only when the route is first visited:

JavaScript
const routes = [
  { path: "/", component: HomeView },  // in the main bundle: needed immediately
  { path: "/reports", component: () => import("../views/ReportsView.vue") },
  { path: "/admin", component: () => import(/* webpackChunkName: "admin" */ "../views/AdminView.vue") }
];

Rules of thumb: keep the landing page and anything every visitor needs in the main bundle, and make rarely visited or heavy pages (admin, reports, editors, charts) lazy. Vue Router handles the loading state for you by simply delaying the navigation until the chunk has arrived, which is one more reason to keep a visible progress indicator in your layout (use router.beforeEach and afterEach to toggle it). For the component-level version of the same idea see Dynamic and Async Components, and for measuring the effect see Build and Load Performance.

Scroll behavior

After a navigation in a classic website, the browser starts at the top of the new page, and Back restores your previous scroll position. In a single-page app you have to ask for that behavior. The router's scrollBehavior option does:

JavaScript
const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;                         // Back/forward: restore
    }
    if (to.hash) {
      return { el: to.hash, behavior: "smooth" };   // /page#section: scroll to it
    }
    return { top: 0 };                              // new page: start at the top
  }
});

The function receives the destination, the origin and the saved position (only set for Back and forward navigations in history mode). It can return a position object or a promise, which is useful when you must wait for a transition to finish. Scroll position saving does not apply in the sandbox preview, so this example is read-only.

Scrolling is only half of the experience for keyboard and screen-reader users: after a route change, focus should move to the new page heading or the main region, and the change should be announced. That is covered in Accessibility in Vue.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In nested routes, what does a child record with path: "" do?

    Without a default child, visiting the parent's own URL renders the layout with an empty RouterView area.
  2. 2. A global beforeEach guard returns false. What happens?

    Returning false cancels the navigation. To send the user elsewhere, return a route location such as a path string or an object.
  3. 3. Why is a route guard that checks meta.requiresAdmin not enough to protect admin data?

    Guards only decide which screen the user sees. Authorization must be enforced on the server for every request.
  4. 4. What is the effect of component: () => import('./ReportsView.vue') on a route?

    A dynamic import lets the bundler split the page into its own file, which keeps the initial download small.

Summary

  • Nested routes use children plus a <RouterView> inside the parent; a URL matches a chain exposed as route.matched, and path: "" is the default child.
  • meta holds your own data on a record (titles, breadcrumbs, requiresAuth) and is readable on route.meta and route.matched.
  • Guards return nothing or true to continue, false to cancel, or a route location to redirect; they can be global, per route or in components.
  • afterEach cannot cancel; use it for analytics and document titles.
  • Guards are a user-experience tool; the server must enforce permissions.
  • Lazy routes with () => import(...) split code per page, and scrollBehavior restores or resets scroll position.

Now let's look at sharing state across the whole app: Sharing State Between Components.