I am trying to access the Vuex store as shown in this article: here
I've wasted a good morning on what I am sure is going to be a simple typo, but It escapes me. Inside the beforeEach() => {} body, I get "store is not defined".
I am using the store from the LoginForm component, and it seems to be there. The Vuex tab in the chrome debugger shows the store contents that I expect. What am I doing incorrect?
Cut-n-paste from the critical code:
src/router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import LoginForm from '@/components/LoginForm'
import HomePage from '@/components/HomePage'
import store from '@/store'
Vue.use(VueRouter)
const router = new VueRouter({
routes: [
{
path: '/login',
component: LoginForm
},
{
path: '/home',
component: HomePage,
meta: {requiresAuth: true}
}
]
})
router.beforeEach((to, from, next) => {
// store is undefined here
const IsAuthenticated = store.getters.IsAuthenticated()
if (to.matched.some(record => record.meta.requiresAuth) && !IsAuthenticated) {
next({path: '/login', query: { redirect: to.fullPath }})
} else {
next()
}
})
export default router
EDIT: The export from the store seems to be ok. By keeping a local reference to the imported store and referencing that, it works. Seems to be contextual in my use of beforeEach().
const lStore = store;
router.beforeEach((to, from, next) => {
// store is undefined here, lStore is good to go
const IsAuthenticated = lStore.getters.IsAuthenticated()
...
})
I have a very similar code and the only relevant difference seems to be that I import the store the following way in router/index.js:
import store from '@/store/index';
My entire router.js is:
import Vue from 'vue';
import Router from 'vue-router';
import ProjectPage from '@/pages/ProjectPage';
import store from '@/store/index';
Vue.use(Router);
const router = new Router({
routes: [
{
path: '/',
name: 'ProjectPage',
component: ProjectPage,
},
],
});
router.beforeEach((to, from, next) => {
// store is defined here
console.log(store);
debugger;
});
export default router;
This was a tail-chasing exercise in the grandest. The problem was that my getter was not called "IsAuthenticated" (and it also wasn't a function). I allowed myself to get duped by my debugger. Restoring all code back to the original post and changing the getter call to
correct
const IsAuthenticated = store.getters.isAuthenticated
incorrect
const IsAuthenticated = store.getters.IsAuthenticated()
In Chrome, putting a breakpoint on that line of code and attempting to inspect 'isAuthenticated' by hovering your mouse over the code yields the original indicated behavior, even though the line evaluates fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With