'How to restrict going back to login page after logged in in vue?
I want restrict users from going to back to login page after he/she logs in. How to do this using guard in routes ?
My code :
guard.js
export default function guard(to, from, next) {
const token = localStorage.getItem('_utoken');
if (token) {
next();
} else {
next('/login');
}
}
and in routes.js I used beforeEnter:guard inside every object except login route object like this
{
path:'/home,
name: 'Home,
component: Home,
beforeEnter: guard,
}
If token exists restrict from going to login page or signup page .
Solution 1:[1]
Instead of adding guard into each and every route, you can add a global guard to all routes:
router.beforeEach((to, from, next) =>
{
const token = localStorage.getItem('_utoken');
if (!to.meta.public)
{
// page requires authentication - if there is none, redirect to /login
if (token) next();
else next('/login');
}
else
{
// Login is supposedly public - skip navigation if we have a token
if (token ? to.path !== '/login' : true) next();
}
});
{
path: '/home',
name: 'Home,
component: Home,
},
{
path: '/login',
name: 'Login',
component: Login,
meta:
{
public: true
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | IVO GELOV |
