import vuex store in router file code example

Example: import vuex store in router file

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

import store from '../store/index'

// Components import...

Vue.use(VueRouter)

const routes = [
// Routes...
]

const router = new VueRouter({
    routes,
    mode: 'history'
});

var user = store.state.user,
    isAuthenticated = user.role,
    isAdmin = () => { return user.role == 'admin' };

router.beforeEach((to, from, next) => {
    if (to.name !== 'auth' && !isAuthenticated) {
        next({ path: '/auth' })
    }
    else if (to.matched.some(route => route.meta.requiresPermission)) {
        if (!isAdmin) {
            next(false)
        } else {
            next()
        }
    } else {
        next()
    }
})

export default router

Tags:

Misc Example