My Vuex store setup in main.js looks like this:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
//initialize the store
const store = new Vuex.Store({
state: {
globalError: '',
user: {
authenticated: false
}
},
mutations: {
setGlobalError (state, error) {
state.globalError = error
}
}
})
//initialize the app
const app = new Vue({
router: Router,
store,
template: '<app></app>',
components: { App }
}).$mount('#app')
In addition to this, I have defined routes for Vue Router in 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 attempting to handle a scenario where if the user
object in Vuex has the authenticated
property set to false
, the router should redirect the user to the login page.
To achieve this, I have written the following logic:
Router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresLogin) && ???) {
// update Vuex state's globalError and then redirect
next("/Login")
} else {
next()
}
})
The issue I am facing is how to access the user
object from the Vuex store inside the beforeEach
function.
While I know that I can include similar guard logic within components using BeforeRouteEnter
, I prefer to define it centrally at the router level instead of cluttering up each component.