·
1 min read
Vue Tip: Use Vuex in Vue Router Navigation Guards
Vue Router allows us to define Navigation Guards.
For example, we can register them globally:
const router = createRouter({ ... })
/**
* to: the target route location in a normalized format being navigated to.
* from: the current route location in a normalized format being navigated away from.
*/
router.beforeEach((to, from) => {
// ...
// explicitly return false to cancel the navigation
return false
})
A common scenario is to redirect an unauthenticated user to the login page if he tries to visit a protected route:
router.beforeEach(async (to, from) => {
if (
// make sure the user is authenticated
!isAuthenticated &&
// ❗️ Avoid an infinite redirect
to.name !== 'Login'
) {
// redirect the user to the login page
return { name: 'Login' }
}
})
If you are using Vuex you probably store the authenticated state in the Vuex store.
You can easily access that store in your guard navigation:
import store from '@/store'
router.beforeEach(async (to, from) => {
const authenticated = store.getters['auth/authenticated']
// redirect the user to login page if he is not authenticated
if (!authenticated && to.name !== 'Login') {
return { name: 'Login' }
}
})
If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:
Vue Tip: Special CSS Selectors
Vue provides some special CSS pseudo-selectors you can use in your Vue SFC.
Vue Tip: Watch Nested Values
The watch options support a dot-delimited path as key to watch nested values.