Implementing straightforward middleware logic and encountering
Encountered an infinite redirection in a navigation guard when transitioning from "/" to "/login". Halting to prevent a Stack Overflow. This issue will cause problems in production if not resolved.
Acknowledged that my code is causing multiple redirects, but struggling to locate the source.
Presenting the router:
import { createWebHistory, createRouter } from 'vue-router'
import store from '@/store'
/* Guest Component */
const Login = () => import('@/components/Login.vue')
const Register = () => import('@/components/Register.vue')
/* Guest Component */
/* Layouts */
const DahboardLayout = () => import('@/components/layouts/Default.vue')
/* Layouts */
/* Authenticated Component */
const Dashboard = () => import('@/components/Dashboard.vue')
/* Authenticated Component */
const routes = [
{
name: "login",
path: "/login",
component: Login,
meta: {
middleware: "guest",
title: `Login`
}
},
{
name: "register",
path: "/register",
component: Register,
meta: {
middleware: "guest",
title: `Register`
}
},
{
path: "/",
component: DahboardLayout,
meta: {
middleware: ["all"]
},
children: [
{
name: "dashboard",
path: '/',
component: Dashboard,
meta: {
title: `Dashboard`
}
}
]
}
]
const router = createRouter({
history: createWebHistory(),
routes, // short for `routes: routes`
})
router.beforeEach((to, from, next) => {
document.title = to.meta.title
if (to.meta.middleware == "all") {
return next();
} else if (to.meta.middleware == "guest") {
if (store.state.auth.authenticated) {
return next({ name: "login" })
} else {
return next()
}
} else if (to.meta.middleware == "auth") {
if (store.state.auth.authenticated) {
return next()
} else {
return next({ name: "login" })
}
}
})
export default router
In the Default.vue component:
<router-link :to="{name:'login'}">Login</router-link>