Search code examples
vue.jsvuex

Vuex Cannot read property of undefined


I am trying to work with global variables with Vuex but also I do keep getting undefined error even I initialize Vuex using Vue.use();.

TypeError: Cannot read property 'isAuth' of undefined

store.js:

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  isAuth: true,
});

main.js:

import store from './store/store';
....
new Vue({
  el: '#app',
  store,
  router,
  render: h => h(App),
.......

I call isAuth to see its value like this: this.$store.isAuth; and this causes the undefined error.

I did initialize Vuex in store.js, but am still having the undefined error. Is there something I am missing?


Solution

  • At a guess, this might work with what you're currently doing: this.$store.state.isAuth but I would do it like below.

    I've not used the store in the way you have before but haven't had issues when using modules, try like this:

    // authModule.js
    const state = {
        isAuth: true
    }
    
    const getters = {
        getIsAuth (state) {
            return state.isAuth
        }
    }
    
    export default {
        state,
        getters
    }
    

    Then register it like so:

    import authModule from './modules/authModule'
    export default new Vuex.Store({
        modules: {
            authModule
        }
    })
    

    Then on your vue instance:

    import {mapGetters} from 'vuex'
    
    computed: {
        ...mapGetters({
            isAuth: 'getIsAuth'
        })
    }
    

    You can now access via this.isAuth. You can also access like: this.$store.state.authModule.isAuth

    This is actually best practice according to their docs as it keeps things tidy when the project gets larger.