Vue3 Fundamentals ยท Vue Router

Navigation and guards

Programmatic navigation and guards

Navigation and guards

Sometimes a link is not enough. After a form submits you navigate from code, and before a protected page opens you check the user is allowed in. Vue Router covers both.

The useRouter() composable gives you the router instance. Call push to navigate and add a history entry, or replace to swap the current one:

<script setup>
import { useRouter } from 'vue-router';

const router = useRouter();
const save = async () => {
  await api.save();
  router.push('/dashboard');
};
</script>

router.back() returns to the previous page, and router.go(n) moves n steps through the history.

A navigation guard runs before a navigation is confirmed. Register a global guard with router.beforeEach, which receives the target route and a next function:

router.beforeEach((to) => {
  if (to.meta.requiresAuth && !isLoggedIn()) {
    return { name: 'login' };
  }
});

Return false to cancel the navigation, or return a route location to redirect. The meta field on a route carries your own data, such as requiresAuth, so guards can decide without hard-coding paths.

You are about to answer a short quiz on programmatic navigation and guards.

  1. The `___()` composable returns the router instance for programmatic navigation.
  2. `router.push('/dashboard')` adds a new entry to the browser history.
  3. `router.___()` navigates without adding a new history entry.
  4. A global navigation guard is registered with `router.beforeEach`.
  5. Returning `false` from a navigation guard cancels the navigation.
  6. A route's `___` field carries your own data, such as `requiresAuth`, for guards to read.