Back
VueMediumNew
How do you set up navigation guards in Vue Router?
beforeEach, beforeEnter, per-route vs global guards
Ideal Answer
Vue Router provides navigation guards at global, per-route, and in-component levels to control navigation, commonly used for auth checks.
JavaScript
// Global guard
router.beforeEach((to, from) => {
if (to.meta.requiresAuth && !isAuthenticated()) {
return { name: 'login' }
}
})
// Per-route guard
const routes = [
{
path: '/admin',
component: Admin,
beforeEnter: (to, from) => { /* ... */ }
}
]
In-component guards (onBeforeRouteLeave, onBeforeRouteUpdate) are also available as Composition API functions for use inside <script setup>.