JAVASCRIPT

Implement Programmatic Navigation with Vue Router 4

Guide users through your Vue 3 application programmatically using `router.push()` for redirection and `beforeEach` navigation guards for authentication or data pre-fetching.

// router/index.js
import { createRouter, createWebHistory } from 'vue-router';

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/HomeView.vue')
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('../views/DashboardView.vue'),
    meta: { requiresAuth: true } // Custom meta field for authentication
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/LoginView.vue')
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

// Global Navigation Guard
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('isAuthenticated'); // Simulate auth check

  if (to.meta.requiresAuth && !isAuthenticated) {
    // If route requires auth and user is not authenticated, redirect to login
    console.log('Redirecting to login: Auth required.');
    next({ name: 'Login' });
  } else if (to.name === 'Login' && isAuthenticated) {
    // If user is authenticated and tries to go to login, redirect to dashboard
    console.log('Already logged in, redirecting to dashboard.');
    next({ name: 'Dashboard' });
  } else {
    // Proceed to the route
    next();
  }
});

export default router;

// views/LoginView.vue (Example component for triggering login)
<template>
  <div>
    <h2>Login</h2>
    <button @click="performLogin">Log In</button>
  </div>
</template>

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

const router = useRouter();

const performLogin = () => {
  // Simulate successful login
  localStorage.setItem('isAuthenticated', 'true');
  console.log('Logged in successfully!');
  router.push({ name: 'Dashboard' }); // Programmatic navigation to Dashboard
};
</script>

// views/DashboardView.vue (Example protected component)
<template>
  <div>
    <h2>Dashboard</h2>
    <p>Welcome, you are logged in!</p>
    <button @click="performLogout">Log Out</button>
  </div>
</template>

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

const router = useRouter();

const performLogout = () => {
  localStorage.removeItem('isAuthenticated');
  console.log('Logged out.');
  router.push({ name: 'Home' }); // Programmatic navigation to Home
};
</script>
How it works: This snippet demonstrates programmatic navigation and global navigation guards in Vue Router 4. The `router.push({ name: 'Dashboard' })` call in `LoginView.vue` redirects the user to the dashboard after a simulated successful login. The `router.beforeEach` global guard intercepts every navigation attempt. It checks if a route requires authentication (via `meta.requiresAuth`) and redirects unauthenticated users to the login page. It also prevents authenticated users from accessing the login page by redirecting them to the dashboard, ensuring a controlled user flow.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs