I have the following Vuex repository (main.js):
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) //init store const store = new Vuex.Store({ state: { globalError: '', user: { authenticated: false } }, mutations: { setGlobalError (state, error) { state.globalError = error } } }) //init app const app = new Vue({ router: Router, store, template: '<app></app>', components: { App } }).$mount('#app')
I also have the following routes defined for Vue-Router (routes.js):
import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter) //define routes const routes = [ { path: '/home', name: 'Home', component: Home }, { path: '/login', name: 'Login', component: Login }, { path: '/secret', name: 'Secret', component: SecretPage, meta: { requiresLogin: true } ]
I am trying to make sure that if the Vuex store user object has the authenticated property false property, ask the router to redirect the user to the login page.
I have it:
Router.beforeEach((to, from, next) => { if (to.matched.some(record => record.meta.requiresLogin) && ???) { // set Vuex state globalError, then redirect next("/Login") } else { next() } })
The problem is that I donβt know how to access the Vuex store user object from inside the beforeEach function.
I know that I may have the router protection logic inside the components using BeforeRouteEnter , but this will clutter up each component. I want to define it centrally at the router level.
Ege ersoz
source share