Validation of routes in VueJS

I am trying to make ceratin routes for certain users so that every user doesnt see the same view. For example, if the user is logged as an admin, he will go directly to '/admin' instead of '/home'. What i´ve achived is right here

index.js - routes file

{
    path: '/',
    name: 'Home',
    component: Home,
    meta: {
      requiresAuth: true,
      user:'normal-user'
    },
    beforeEnter: (to, from, next) => {
      console.log(from)
      if(from.path == '/admin' || from.path == '/forms' || from.path == '/steps') {
        next('/admin')
      }
      else 
        next()
    }
  }

Keep in mind that I have a /forms route and /steps.

What I'm trying to achiveve is that if the user came from the '/admin' route, when he tries to go to '/' he will be 're-directed' to '/admin'.

I´ve managed to do this but I know it isn't the best way to implement it. Any suggestions?

Upvotes: 0

Views: 565

Answers (1)

aron.duby
aron.duby

Reputation: 2261

Sounds like you want a navigation guard:

https://router.vuejs.org/guide/advanced/navigation-guards.html

router.beforeEach((to, from, next) => {
    if (from.path === 'admin' && to.path === '/') {
        next('/admin');
    } else {
        next();
    }
});

Upvotes: 2

Related Questions