I have a vue router like this:
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
function guard (to, from, next) {
if (localStorage.getItem('jwt')) {
next()
} else {
next('/login')
}
}
function admin (to, from, next) {
if (localStorage.getItem('admin') && localStorage.getItem('admin') !== 'false' && localStorage.getItem('jwt')) {
next()
} else {
next('/noadmin')
}
}
export default new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'home',
beforeEnter: guard,
meta: { layout: 'default' },
component: () => import('@/components/dashboard.vue')
},
{
path: '/datacollector',
name: 'datacollector',
beforeEnter: guard,
meta: { layout: 'default' },
component: () => import('@/components/datacollector.vue')
},
{
path: '/licensing',
beforeEnter: admin,
name: 'licensing',
component: () => import('@/components/licensing.vue')
},
{
path: '*',
name: '404',
component: require('@/pages/404.vue').default
}
]
})
My problem now is the following, if there is an entry localStorage.getItem('datacollector') it should only point to the path /datacollector and /logout. So when he logs in, the login page throws him to the path /datacollector. But he should also be able to call logout. For the other users, it should be that they are allowed to call everything. How do I adjust the function guard, no matter what I try I always end up with a loop. Thank you.
Assuming you want to throw the user to /datacollector route from any route, if there is an entry for localStorage.getItem('datacollector'), except for /logout route.
You can simply check for to.path and redirect the user accordingly:
function guard (to, from, next) {
if (localStorage.getItem('jwt')) {
if (localStorage.getItem('datacollector')) {
if (to.path != '/datacollector' && to.path != '/logout'){
next('/datacollector');
} else {
next();
}
} else {
next();
}
} else {
next('/login')
}
}