| | |

Vue Router 09 🧭 Composition API & Reactivity — Mastering useRoute(), useRouter(), onBeforeRouteLeave, onBeforeRouteUpdate, and useLink()

⏱️ Estimated read: 11 min | |

The introduction of the Composition API in Vue 3 fundamentally changed how developers interact with the router. In the traditional Options API, the router and current route were accessed through this.$router and this.$route. However, in the <script setup> environment, the this context is unavailable. To bridge this gap, Vue Router provides a suite of composables that inject the router’s state and functionality directly into the setup function, maintaining full reactivity and TypeScript support.

These composables do more than just provide access to variables; they enable a more modular way of writing navigation logic. Instead of being confined to component-level options, developers can now wrap routing logic into custom, reusable functions (hooks). This allows for complex patterns like “useAuthRedirect” or “usePageTracking” that can be shared across disparate parts of an application. Furthermore, the reactive nature of the route object in the Composition API ensures that components respond instantly to changes in parameters, queries, and hash values.

This chapter details the core composables that define modern Vue navigation. We will explore useRoute() for state inspection and useRouter() for programmatic movement. We will also examine the lifecycle hooks onBeforeRouteLeave and onBeforeRouteUpdate, which replace the older in-component guards. Finally, we will cover the advanced useLink() composable, which allows for the creation of completely custom navigation components that mimic the behavior of the standard <router-link>.

Key point: The Composition API composables (useRoute and useRouter) provide a reactive and decoupled way to access routing state and programmatic navigation within <script setup>, allowing for better logic encapsulation and reusability.


Why exists

The this Context Problem. In <script setup>, there is no this. Therefore, the traditional $router and $route properties are unreachable. The composables useRouter() and useRoute() were created to provide a way to “inject” the router instance and current route state into the local scope of the setup function.

The Logic Encapsulation Problem. Before the Composition API, routing logic (like guarding a form or reacting to a parameter change) was tied to component options. If you wanted to reuse a “confirm before leave” logic across five different forms, you had to use mixins, which are difficult to track and debug. Composables allow you to extract this logic into standalone functions.

The Reactivity Orchestration Problem. The route object is a complex, nested structure. In the Composition API, useRoute() returns a reactive object where properties like params and query are tracked by Vue’s reactivity system. This makes it significantly easier to create computed properties that derive their values directly from the URL.

The Custom UI Component Problem. Sometimes, a standard <router-link> isn’t enough. You might need a custom button component from a UI library (like Vuetify or PrimeVue) to behave exactly like a link, including handling active classes and “Open in new tab” behavior. useLink() exposes the internal logic of a router link so you can build your own.

The TypeScript Integration Problem. Traditional Options API properties often require complex shim files for proper typing. The Composition API composables are built with TypeScript in mind, providing autocompletion for route names, parameters, and custom meta fields directly within the IDE, reducing runtime errors.


a. useRoute() and useRouter(): State vs. Action

In the Composition API, we separate the “state” of the current URL from the “action” of navigating to a new one. useRoute() is used for the former. It returns the current route location object, which contains the path, params, query, and meta fields. This object is reactive, meaning if the user navigates from /user/1 to /user/2, the route.params.id value will update automatically.

import { useRoute } from 'vue-router';
import { computed } from 'vue';

const route = useRoute();

// Accessing params reactively
const userId = computed(() => route.params.id);

// Accessing query strings
const searchQuery = computed(() => route.query.q);

While useRoute() is for reading, useRouter() is for writing. It returns the router instance, which contains methods like push, replace, go, and back. This is what you use when you need to trigger a navigation based on a user action, like clicking a button or submitting a form.

import { useRouter } from 'vue-router';

const router = useRouter();

const handleLogin = () => {
  // Perform login logic...
  router.push({ name: 'dashboard' });
};

One critical distinction is that you should never destructure useRoute(). Doing so (e.g., const { params } = useRoute()) will break reactivity because params is a property of the reactive route object. Always access properties through the route variable or use toRefs if destructuring is absolutely necessary.


b. Navigation Hooks: onBeforeRouteLeave and onBeforeRouteUpdate

The Composition API provides equivalent hooks for the in-component navigation guards. These are imported directly from vue-router and can be called anywhere within the setup() function. onBeforeRouteLeave is triggered when the user is navigating away from the current component. It is most commonly used for “unsaved changes” prompts.

import { onBeforeRouteLeave } from 'vue-router';

onBeforeRouteLeave((to, from) => {
  const answer = window.confirm('Do you really want to leave? You have unsaved changes!');
  // Cancel the navigation by returning false
  if (!answer) return false;
});

onBeforeRouteUpdate is triggered when the route changes but the component is reused. This happens most often with dynamic segments, such as moving from /post/1 to /post/2. Because the component isn’t destroyed and recreated, the onMounted hook doesn’t run again. This hook allows you to react to the parameter change and fetch new data.

import { onBeforeRouteUpdate } from 'vue-router';

onBeforeRouteUpdate(async (to, from) => {
  // React to the parameter change
  if (to.params.id !== from.params.id) {
    await fetchPostData(to.params.id);
  }
});

These hooks have a significant advantage over the Options API versions: you can have multiple instances of them in a single component. This is useful if you are using multiple composables that each need to register their own cleanup or update logic, leading to much cleaner and more modular code.


c. useLink(): Creating Custom Link Components

useLink() is an advanced composable designed for developers building custom components that need to behave like <router-link>. It takes a “props” object (similar to the props passed to router-link) and returns everything needed to render a link: the calculated href, the navigate function, and boolean flags like isActive and isExactActive.

import { RouterLink, useLink } from 'vue-router';

// Inside a custom component
const { 
  href, 
  navigate, 
  isActive, 
  isExactActive 
} = useLink({ to: '/dashboard' });

The navigate function returned by useLink() is particularly important. It handles the actual navigation while respecting the browser’s default behaviors, such as preventing navigation if the user is holding the Ctrl or Cmd key to open the link in a new tab. This ensures your custom component feels native to the web.

This composable is the backbone of high-end Vue UI libraries. It allows a developer to take a complex MyFancyButton component and give it first-class routing capabilities without having to manually manage event listeners or state calculations. It essentially exposes the internal engine of Vue Router’s linking system for public use.


Complete Example Session

// ============================================
// PART 1: CORE IMPORTS
// ============================================
import { ref, computed, watch } from 'vue';
import { useRoute, useRouter, onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router';

// ============================================
// PART 2: SETUP ROUTE AND ROUTER
// ============================================
const route = useRoute();   // Access reactive state
const router = useRouter(); // Access navigation methods

// ============================================
// PART 3: REACTIVE PARAMETERS
// ============================================
const productId = computed(() => route.params.id);
const category = computed(() => route.query.cat);

// ============================================
// PART 4: PROGRAMMATIC NAVIGATION
// ============================================
const goBack = () => router.back();
const goToCheckout = () => router.push({ name: 'checkout' });

// ============================================
// PART 5: THE LEAVE GUARD (UNSAVED CHANGES)
// ============================================
const isEditing = ref(false);
onBeforeRouteLeave((to, from) => {
  if (isEditing.value) {
    return window.confirm('Discard your changes?');
  }
});

// ============================================
// PART 6: THE UPDATE GUARD (DATA REFETCH)
// ============================================
onBeforeRouteUpdate(async (to) => {
  console.log('Switching to product:', to.params.id);
  // Perform API call here...
});

// ============================================
// PART 7: DYNAMIC TITLES VIA META
// ============================================
watch(() => route.meta, (newMeta) => {
  document.title = newMeta.title || 'Default Shop';
}, { immediate: true });

// ============================================
// PART 8: CUSTOM LINK LOGIC (COMPOSABLE)
// ============================================
import { useLink } from 'vue-router';
const useCustomLink = (target) => {
  const { navigate, isActive } = useLink({ to: target });
  return { navigate, isActive };
};

// ============================================
// PART 9: REDIRECT LOGIC
// ============================================
const handleUnauthorized = () => {
  router.replace({ name: 'login' });
};

// ============================================
// PART 10: REACTION TO HASH
// ============================================
const currentSection = computed(() => route.hash);

The logic above demonstrates a complete lifecycle: inspecting the route, navigating programmatically, guarding state, refetching on updates, and using custom link logic—all within the Composition API.


Quick Reference

Primary Composables

ComposableReturnsPurpose
useRoute()RouteLocationNormalizedAccess current path, params, query, meta
useRouter()Router instanceTrigger navigation (push, replace, etc.)
useLink()Object with href, navigate, isActiveBuild custom link components

Composition API Hooks

HookTimingAccess to this?
onBeforeRouteLeaveBefore leaving current routeNo (use local refs)
onBeforeRouteUpdateWhen route changes, component reusedNo (use local refs)

useLink Return Object

PropertyTypeDescription
hrefstringThe resolved URL string
navigatefunctionFunction to trigger the navigation
isActivebooleanTrue if route or child is active
isExactActivebooleanTrue if exactly on this route
routeobjectThe resolved route object

Best Practices

✅ Do This:

// Access params through a computed property for reactivity
const id = computed(() => route.params.id);                   // ✅
// Use onBeforeRouteUpdate to fetch data when params change
onBeforeRouteUpdate(to => fetchData(to.params.id));           // ✅
// Use useRouter for actions triggered by logic (e.g. login)
router.push('/dashboard');                                    // ✅
// Keep the whole 'route' object for reactivity
const route = useRoute();                                     // ✅

❌ Don’t Do This:

// Destructure useRoute() - this kills reactivity
const { params } = useRoute();                                // ❌
// Use window.location instead of useRouter
window.location.href = '/new-page';                           // ❌
// Fetch data only in onMounted for dynamic routes
onMounted(() => fetchData(route.params.id));                  // ❌
// (Missing onBeforeRouteUpdate means it won't update on /1 to /2)

Common Pitfalls

PitfallWhy It HappensFix
Broken ReactivityDestructuring useRoute() propertiesAccess properties directly: route.params.x
stale data on /:idonMounted only runs once for reused componentsUse onBeforeRouteUpdate or watch(route)
useLink NavigationManually setting window.location in custom linksUse the navigate function from useLink
useRoute in GuardsTrying to use useRoute inside beforeEachUse the to and from arguments of the guard
Setup contextCalling composables outside of setup()Always call them at the top level of setup

Real-World Examples

1. Reactive Search Query

const query = computed(() => route.query.search);

2. Confirm Navigation Away

onBeforeRouteLeave(() => window.confirm('Discard?'));

3. Parameter Watcher

watch(() => route.params.id, (id) => loadUser(id));

4. Conditional Redirect

if (!user.token) router.replace('/login');

5. Breadcrumb Generator

const breadcrumbs = computed(() => route.matched.map(r => r.name));

6. Custom Tab Link

const { navigate, isActive } = useLink({ to: '/tabs/1' });

7. Active Class for Sidebar

<div :class="{ active: isActive }">Menu Item</div>

8. Dynamic Page Header

const title = computed(() => route.meta.title || 'App');

9. Returning to Previous Page

const goBack = () => router.go(-1);

10. Casting Params to Number

const id = computed(() => parseInt(route.params.id));

Visual

Composition API Bridge

┌──────────────────────────────────────────────────────────┐
│ VUE ROUTER CORE                                          │
└───────────────┬──────────────────────────┬───────────────┘
                │                          │
                ▼                          ▼
      ┌───────────────────┐      ┌───────────────────┐
      │   useRoute()      │      │   useRouter()     │
      ├───────────────────┤      ├───────────────────┤
      │ READ STATE        │      │ WRITE ACTIONS     │
      │ (params, query)   │      │ (push, replace)   │
      └─────────┬─────────┘      └─────────┬─────────┘
                │                          │
                └────────────┬─────────────┘
                             │
                             ▼
                ┌──────────────────────────┐
                │ YOUR COMPONENT (setup)   │
                │ Reacts to URL Changes    │
                └──────────────────────────┘

Reused Component Lifecycle

URL: /post/1  ───►  URL: /post/2
      │              │
      ▼              ▼
onMounted (runs)   onMounted (SKIPPED)
      │              │
      ▼              ▼
               onBeforeRouteUpdate (runs)
               (Refetch Data Here)

useLink Flow

┌──────────────────────────────────────────────────────────┐
│ CustomComponent.vue                                      │
│                                                          │
│ Input: { to: '/settings' }                               │
│                                                          │
│ Result:                                                  │
│ - href: "/settings"                                      │
│ - isActive: true/false                                   │
│ - navigate: function() { ...router logic... }           │
└──────────────────────────────────────────────────────────┘

Summary

ItemValue
Route StateuseRoute()
Programmatic NavuseRouter()
Reused Comp HookonBeforeRouteUpdate
Leave Comp HookonBeforeRouteLeave
Custom Link APIuseLink()
ReactivityFully supported via Proxy
DestructuringNot recommended (breaks reactivity)
Setup UsageTop-level call only

Key takeaways:

  • useRoute is the window into the URL. Use it to extract parameters, query strings, and metadata. Always treat it as a reactive object and avoid destructuring to keep your UI in sync with the address bar .
  • useRouter is the driver’s seat. It provides the tools to move through history, whether it’s a simple push, a history-replacing replace, or moving back and forth with go .
  • Hooks replace component options. onBeforeRouteLeave and onBeforeRouteUpdate provide the same power as traditional in-component guards but with the added flexibility of being used inside reusable composables .
  • Reused components need special care. Since components are not re-mounted when dynamic parameters change, onBeforeRouteUpdate or watching route.params is essential for updating the view .
  • useLink democratizes routing logic. It allows you to build custom, accessible navigation components that share the same underlying logic as the official RouterLink .
  • Composition API promotes modularity. Routing logic can now be extracted into standalone files, making large-scale application architecture significantly more manageable and testable .

Remember: Composables in Vue Router turn routing from a component-bound configuration into a flexible, reactive set of tools that you can inject exactly where they are needed.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!