Cannot read properties of undefined (reading '$store')

11,036

Inside of vue router, you do not have a vue instance. Therefore there is no way to access this.$store.state. In order to access your store you need to include vuex into the router.

import store from '@/store/index.js';

Then to call data from the store you will call the store variable we just imported. For example

if(!store.state.user){
 next('/401');
}

For you case it would look something like this:

import store from '@/store/index.js';

{
  path: '/',
  name: 'login',
  component: () => import( /* webpackChunkName: "hours" */ '../views/login.vue'),
  meta: {
    hideNavbar: true,
  },
  beforeEnter: (to, from, next) => {
    if (store.state.authenticated.admin === true) {
      next('/home');
    } else {
      next(false);
    }
  }
}

I'd suggest looking at this answer as well: Accessing Vuex store in Router

Share:
11,036

Related videos on Youtube

Maseeha Tasneem
Author by

Maseeha Tasneem

Updated on January 01, 2023

Comments

  • Maseeha Tasneem
    Maseeha Tasneem over 1 year

    Hii I'm getting this error Cannot read properties of undefined (reading '$store'): This is my router(index.js)

    {
      path: '/',
      name: 'login',
      component: () => import( /* webpackChunkName: "hours" */ '../views/login.vue'),
      meta: {
        hideNavbar: true,
      },
      beforeEnter: (to, from, next) => {
        if (this.$store.state.authenticated.admin === true) {
          next('/home');
        } else {
          next(false);
        }
      }
    

    In this above code I'm Struggling to navigate to the home page...getting this error. here`TypeError: Cannot read properties of undefined (reading '$store')