Navigation guards allow you to redirect or cancel navigation — perfect for authentication checks and unsaved-changes warnings.
// src/router/index.js
router.beforeEach((to, from) => {
const isAuthenticated = !!localStorage.getItem('token')
if (to.meta.requiresAuth && !isAuthenticated) {
return { name: 'login' } // redirect
}
})
const routes = [
{
path: '/dashboard',
component: DashboardView,
meta: { requiresAuth: true },
beforeEnter: (to, from) => {
if (!hasPermission(to.meta.permission)) {
return { name: 'forbidden' }
}
},
},
]
import { onBeforeRouteLeave } from 'vue-router'
const isDirty = ref(false)
onBeforeRouteLeave((to, from) => {
if (isDirty.value) {
const ok = window.confirm('You have unsaved changes. Leave anyway?')
if (!ok) return false // cancel navigation
}
})