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.