Geoff
Geoff

Reputation: 6629

Guarding child routes in vuejs

Am trying to guard child routes from the parent routes but this fails

    export default new Router({
    routes: [
    //frontend routes
    {
      {path: 'auth', component: Auth, children: authroutes,
        beforeEnter: (to, from, next) => {
        // check if user is a guest or loggedin
        auth.canAccess(permissions.is_guest)
          .then((res) => {
            if (res.data.status) {
              next();
            } else {
              router.push('/auth/not-allowed');
            }
          })
       }}
      ]
     }
   ]
 })

Now on my child routes

authroutes.js

const authroutes = [
  {path: '', redirect: 'login'},
  {path: 'login', component: Login, name: "login" },
];

But when i place the above beforeenter on the child routes it works but it leads to alot of code duplication.

How can i guard children from the parent route

eg: guard /auth/login and /auth/register

Upvotes: 1

Views: 3988

Answers (1)

Vamsi Krishna
Vamsi Krishna

Reputation: 31362

Just use route's meta field for the fields you want to guard like this:

const authroutes = [
    {path: '', redirect: 'login', meta: {requiresAuth: true}},
    {path: 'login', component: Login, name: "login" , meta: {requiresAuth: true}},,
];

then configure your router to check if the route has a specified meta field and perform your redirect logic

router.beforeEach((to, from, next) => { 
    if (to.matched.some(record => record.meta.requiresAuth)) { 
        auth.canAccess(permissions.is_guest)
              .then((res) => {
                if (res.data.status) {
                      next();
                } else {
                     next('/auth/not-allowed');
                }
              })
    }else { 
        next() // make sure to always call next()! 
    } 
});

Check out more info here: Route meta fields

Upvotes: 8

Related Questions