Navigation Guards and Route Metadata
🎯 Introduction
By the end of this article, you will be able to use advanced routing features in Vue 2: control access with navigation guards, manage page titles with route metadata, and add animated page transitions. These techniques help make your SPA smoother, more polished, and easier to use.
🔐 Introducing Navigation Guards
Vue Router in Vue 2 provides navigation guards for running logic during navigation, such as checking permissions or preprocessing data. There are three main categories:
- Global guards (apply to all routes)
- Per-route guards (apply to a specific route)
- In-component guards (defined within route components)
Let's look at how these guards are used.
🌟 Global Before Guards: router.beforeEach
A global before guard runs when navigation begins. It is commonly used for permission checks and login requirements. Register it by calling beforeEach on the router instance.
router.beforeEach((to, from, next) => {
const isLogin = Boolean(localStorage.getItem('token'));
if (isLogin) {
next();
} else {
next('/login'); // Redirect unauthenticated users to the login page
}
});
router.beforeEach, call next() when navigation should proceed. Otherwise, navigation cannot complete.🌟 Per-Route Guards (beforeEnter)
A route can define its own guard. This straightforward approach is useful for logic specific to a single route.
const routes = [
{
path: '/admin',
component: () => import('@/components/Admin.vue'),
beforeEnter: (to, from, next) => {
const isLogin = Boolean(localStorage.getItem('token'));
if (isLogin) {
next();
} else {
next('/login'); // Redirect unauthenticated users to the login page
}
},
},
];
This guard runs only when entering /admin, making it useful for fine-grained access control.
🏷️ Route Metadata (meta)
The meta field stores custom route data, such as permissions, page titles, or caching flags. Navigation guards and component logic can use this data to implement different behaviors.
const routes = [
{
path: '/dashboard',
component: Dashboard,
meta: {
requiresAuth: true,
title: 'User Dashboard',
keepAlive: true,
},
},
];
Page Titles
Use a navigation hook to update the page title dynamically:
router.afterEach(to => {
document.title = to.meta.title || 'Default Title';
});
🎨 Page Transitions
Vue's <transition> component makes it easy to animate page changes for smoother navigation.
Basic Example
<template>
<div id="app">
<transition name="fade" mode="out-in">
<router-view />
</transition>
</div>
</template>
<style>
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter,
.fade-leave-to {
opacity: 0;
}
</style>
More Complex Animations
Combine CSS animations or JavaScript hooks to create richer effects, such as sliding left or right or flipping a page.
.slide-enter-active {
animation: slide-in 0.3s forwards;
}
.slide-leave-active {
animation: slide-out 0.3s forwards;
}
@keyframes slide-in {
from {
transform: translateX(100%);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}
@keyframes slide-out {
from {
transform: translateX(0);
opacity: 1;
}
to {
transform: translateX(-100%);
opacity: 0;
}
}
Use this with <transition name="slide" mode="out-in">.
❓ Questions and Answers
Q1: How do global guards differ from per-route guards?
Global guards apply to all routes and suit shared logic. Per-route guards apply only to a specific route and suit route-specific behavior.
Q2: Why can't beforeRouteEnter access the component instance directly?
The component has not been created yet. Access the instance through a callback passed to next(vm => {}).
Q3: How do you set the page title dynamically from route metadata?
In router.afterEach, use to.meta.title to update document.title.
🧪 Exercises
Complete the following template to check access permissions and update page titles dynamically.
import Vue from 'vue';
import Router from 'vue-router';
import Home from '@/components/Home.vue';
import Login from '@/components/Login.vue';
import Dashboard from '@/components/Dashboard.vue';
Vue.use(Router);
const router = new Router({
routes: [
{ path: '/', component: Home, meta: { title: 'Home' } },
{ path: '/login', component: Login, meta: { title: 'Login' } },
{ path: '/dashboard', component: Dashboard, meta: { requiresAuth: true, title: 'Dashboard' } },
],
});
// TODO: Add a global before guard to redirect unauthenticated users visiting /dashboard to the login page
// TODO: Add an afterEach hook to set the page title from the route's meta.title
export default router;
🎉 You now know how to use navigation guards, route metadata, and page transitions!
Core Routing Features Explained
A beginner-friendly guide to dynamic route matching, nested routes, redirects, aliases, programmatic navigation, and history and hash modes in Vue 2.
Route Optimization and Lazy Loading
Learn route lazy loading and code splitting in Vue 2 to improve application performance and the user experience.
