JAVASCRIPT
Programmatic Navigation & Route Guards in Vue Router
Master programmatic navigation with Vue Router's `router.push()` and secure routes using `beforeEach` navigation guards in Vue 3 applications.
// router/index.js (excerpt)
import { createRouter, createWebHistory } from 'vue-router';
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', component: () => import('../views/Home.vue') },
{ path: '/dashboard', component: () => import('../views/Dashboard.vue'), meta: { requiresAuth: true } },
{ path: '/login', component: () => import('../views/Login.vue'), name: 'Login' },
],
});
router.beforeEach((to, from) => {
const isAuthenticated = localStorage.getItem('userToken'); // Simulate auth check
if (to.meta.requiresAuth && !isAuthenticated) {
// If the user is not authenticated and trying to access a protected route
return { name: 'Login', query: { redirect: to.fullPath } };
}
});
// MyComponent.vue (for programmatic navigation)
<template>
<button @click="goToDashboard">Go to Dashboard</button>
<button @click="goToLoginPage">Login</button>
</template>
<script setup>
import { useRouter } from 'vue-router';
const router = useRouter();
function goToDashboard() {
router.push('/dashboard');
}
function goToLoginPage() {
router.push({ name: 'Login' });
}
</script>
How it works: This snippet illustrates two crucial Vue Router features: programmatic navigation and route guards. `router.push()` allows developers to navigate users imperatively, useful for form submissions or button clicks. The `router.beforeEach` global navigation guard intercepts navigation attempts, enabling powerful features like authentication checks or redirects based on user roles before a route is accessed, enhancing application security and user experience.