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 tip, follow me on Twitter to get notified about new tips, blog posts and more content from me.
Alternatively (or additionally), you can also subscribe to my newsletter.
Sie haben einen Fehler in diesem Artikel gefunden? Sie möchten gerne etwas klarstellen, aktualisieren oder hinzufügen?
Alle meine Artikel können auf Github editiert werden. Jeder Fix ist willkommen, egal wie klein er sein mag!
Ändern auf Github