D
D
Dmitry Kuznetsov2018-05-03 15:45:10
Vue.js
Dmitry Kuznetsov, 2018-05-03 15:45:10

Why is vuex $store throwing "undefined"?

Hai. I resumed training Vue.JS, and then there was a problem:
There is a route file in which all routes and authorization checks are registered:

import Vue from 'vue'
import VueRouter from 'vue-router'
import Meta from 'vue-meta'

Vue.use(VueRouter)
Vue.use(Meta)

/**
 * Для пользователей
 * @constructor
 */
const Home = () => import('../components/home.vue')

/**
 * Для гостей
 * @constructor
 */
const Welcome = () => import('../components/welcome.vue')

/**
 * Страница ошибок
 * @constructor
 */
const NotFound = () => import('../components/errors/NotFound.vue')

const router = new VueRouter({
  mode: 'history',
  routes: [
    /* Нейтральные страницы */
    { path: '/', name: 'home', component: Home, meta: {isAuth: true} },
    { path: '/welcome', name: 'welcome', component: Welcome, meta: {guest: true} },

    {
        /* 404 - Page not found */
        path: '/404',
        name: 'notfound',
        component: NotFound
    }, {
        path: '*',
        redirect: '/404'
    }
  ],

  linkActiveClass: '',
  linkExactActiveClass: ''
});

console.log(this.$store)    // Пробуем получить хоть что-то

// Тут будет проверка на авторизацию и выдачу необходимого роута
// router.beforeEach(
// 	(to, from, next) => {
// 		if(to.matched.some(record => record.meta.isGuest)){
// 			if(this.$store.state.auth.check){
// 				next({
// 					path: '/'
// 				})
// 			} else next()
// 		}else if(to.matched.some(record => record.meta.isAuth)){
// 			if(!this.$store.state.auth.check){
// 				next({
// 					path: '/auth/login'
// 				})
// 			}else{
// 				next()
// 			}
// 		} else next()
// 	}
// )

export default router

Vuex itself:
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const state = {
  auth: {
    check: false,
    user: {}
  }
}

export default new Vuex.Store({
  strict: process.env.NODE_ENV !== 'production',

  state,

  getters: {
    /**
     * Проверка пользователя на авторизацию
     * @param state
     * @returns {boolean}
     */
    authCheck: (state) => {
      if(state.auth.check){
        return true
      }

      return false
    }
  },

  mutations: {},
})

And when I want to get getter data, I can’t in the route file - undefined writes. But, for example, in the home.vue file, in created(), my data is displayed. As I just did not try to get the values ​​​​(as someone advised me a long time ago):
Vue.store
Vue.$store
this.store
this.$store

Thank you in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artem0071, 2018-05-03
@dima9595

Because you didn’t specify anywhere in the router where to get this store from.
Import it separately

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question