I have the following Vuex store (main.js):
import Vue from \'vue\'
import Vuex from \'vuex\'
Vue.use(Vuex)
//init sto
I found that the store was not available to me in router.py when using the guard router.beforeEach, however by changing the guard to router.beforeResolve, then the store was available.
I also found that by awaiting the import of the store in the guard router.beforeEach, I was then able to successfully use router.beforeEach. I provide an example of that below the router.beforeResolve code.
So to keep my example simular to the OP's question the following is how it would have worked for me. I am using vue-router 3.0.2 and vuex 3.1.0.
import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'; //or use a full path to ./store
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 }
]
const router = new VueRouter({
routes //es6
})
router.beforeResolve((to, from, next) => {
const user = store.state.user.user; //store with namespaced modules
if (to.matched.some(record => record.meta.requiresLogin) && user.isLoggedIn) {
next() //proceed to the route
} else next("/login") //redirect to login
next()
})
export default router;
I also found that I could get router.beforeEach to work by await-ing the loading of the store in the beforeEach guard.
router.beforeEach(async (to, from, next) => {
const store = await import('@/store'); //await the store
const user = store.state.user.user; //store with namespaced modules
if (to.matched.some(record => record.meta.requiresLogin) && user.isLoggedIn) {
.... //and continue as above
});