0

I'm struggling to do a check against a store variable/property in the route beforeEach guard.. I cannot seem to figure out how to access the store's properties..

My code :

import Vue from 'vue'
import Router from 'vue-router'
import store from "@/components/store.js"
... other imports..

Vue.use(Router);

const routes = [
    { path: '/', component: NluEditor },
    { path: '/nlueditor', component: NluEditor },
    { path: '/login', component: Login },
    { path: '/logout', component: Logout}
];

const router = new Router({
    routes
});

router.beforeEach((to, from, next) => {
    if(to.path != '/login') {
        console.log(store)
        if (store.state.loggedInUser) {  // cannot seem to access store ? 
            console.log("You are logged in :) Go to requested page ")
            next()
        }
        else {
            console.log("Not logged in.. redirecting....")
            next('login');
        }
    }
  })

const app = new Vue({
    el: '#app',
    router,
    store,

    render: h => h(App)
})
1
  • Can you share your store.js code please Commented Mar 2, 2018 at 4:49

2 Answers 2

2

You can access the store. There is no problem with that as you are importing it.

The problem is with how you are accessing state.loggedInUser. You might be using modules in your store and loggedInUser might belong to a module. So to access it you need to refer to the module name that loggedInUser belongs to like this:

if (store.state.moduleName.loggedInUser) {
  ? console.log("You are logged in :) Go to requested page ") 
    next() 
}

Replace moduleName with the name of the module loggedInUser belongs to.

Sign up to request clarification or add additional context in comments.

2 Comments

Actually you are right!... I completely ignored that the logic for userhandling was in a different module.. Thanks ! :)
I have been looking for this answer for days... thank you SO MUCH!!!!!!
0

I was able to achieve this in a recent app by changing store.state.loggedInUser for store.getters.loggedInUser.

Essentially telling it to call the getter method directly instead of a mapping to the method through the state.

1 Comment

Will try this tomorrow morning norwegian viking time :) thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.