Recently, I have been diving into learning Vuex and creating an authentication module. Following a tutorial, I reached a point where I needed to use the store in the router. However, after importing my store at the top of the router index.js file, I noticed that I couldn't access getters as they were showing up as undefined.
The strange thing is that the store works perfectly fine in Vue components. So, why am I facing this issue? Could it be because the store is not properly initialized when the router is created? The tutorial I followed didn't mention any problems like this.
This is how my router/index.js looks:
import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
import store from '../store'
Vue.use(VueRouter)
export default function() {
const Router = new VueRouter({
scrollBehavior: () => ({ x: 0, y: 0 }),
routes,
mode: process.env.VUE_ROUTER_MODE,
base: process.env.VUE_ROUTER_BASE,
})
Router.beforeEach((to, from, next) => {
if(to.matched.some(record => record.meta.requiresAuth)) {
if (store.getters.isLoggedIn) {
next()
return
}
next('/login')
} else {
next()
}
})
return Router
}
And here's my store/index.js:
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import getters from './getters'
import mutations from './mutations'
import actions from './actions'
Vue.use(Vuex)
export default function() {
const Store = new Vuex.Store({
modules: {},
namespaced: true,
getters,
mutations,
actions,
state,
strict: process.env.DEV,
})
return Store
}