I have a Login page that is bound to the path '/'
. And if I login, I go to '/home'
. The problem is that if I manually type the path '/'
in the url of the browser, I go to the login page again. Is there a way to redirect me to '/home'
if am already logged in? I know that I can use redirect like in the code below, but I am not sure where should I declare the a variable called isLoggedIn
and how to use it. Or maybe it could be better do it in the <script>
section of the Login
page.
{
path: '/',
name: 'Login',
component: Login,
redirect: to => {
return {path: '/orders'}
}
}
CodePudding user response:
What you are looking for is called navigation guard
:
you will find more information in the vue router documentation https://router.vuejs.org/guide/advanced/navigation-guards.html#global-before-guards
And here is a quick example extracted from this page
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' }
}
})