VueJS 2, router guard

My index route is defined as:

{ path: '/', adminOnly: false, component: Main },

Is there a way to access the 'adminOnly' property?

There seems to be no way of doing so in this block of code:

routes.beforeEach((to, from, next) => {
    console.log(to)
    next();
});

My routes file:

import Vue from 'vue';
import VueRouter from 'vue-router';

import Main from '../components/Main.vue';
import About from '../components/About.vue';

const NotFoundException = {
    template: '<div>Route Was Not Found</div>'
};

Vue.use(VueRouter);

const routes = new VueRouter({
    mode: 'history',
    hashbang: false,
    linkActiveClass: 'active',
    base: '/jokes',
    routes: [
        { path: '/', adminOnly: false, component: Main },
        { path: '/about', adminOnly: false, component: About },
        { path: '*', adminOnly: false, component: NotFoundException }
    ]
});
routes.mode = 'html5';

routes.beforeEach((to, from, next) => {
    // CHECK IF ADMINONLY EXISTS
    next();
});

export default routes;

I did get a solution by adding a mixin of adminOnly.js which has the following code in it: But then again, the mixin has to be added to each component if I was to redirect the user to the login page if not admin. //Just a test var isAdmin = false;

export default {
        beforeRouteEnter (to, from, next) {
            if(!isAdmin) {
                next((vm) => {
                   vm.$router.push('/login');
                });
            }
        }
    }

Answers:

Answer

Yes there is better way to handle this. Every route object can have meta field. Just wrap adminOnly property in meta object:

 routes: [
        { path: '/', meta: { adminOnly: false }, component: Main },
        { path: '/about', meta: { adminOnly: false }, component: About },
        { path: '*', meta: { adminOnly: false }, component: NotFoundException }
    ]

Check route for admin rights:

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.adminOnly)) {
    // this route requires auth, check if logged in
    // if not, redirect to login page.
  }
}

For more please check docs and I created little example on jsFiddle

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.