4

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?

0

1 Answer 1

4

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.

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

6 Comments

Thanks for the answer. I no longer get the error but I still get undefined as the value of isAuth. Should I see the value or is it normal to see the value as undefined?
You should never see undefined, no. If you console.log(this) from your vue component, take a look and you should see $store. Does it have a value? You should be able to drill down into the state as well and see what value it has. That'd be a good place to start.
I modified a little bit more and I now am be able to see $store wherever I want. Thank you again for your time!
how do you this if you're using straight up js instead of .vue files?
@qodeninja Sorry, this isn't something I've done before so don't know. The Vuex website should have some information though.
|

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.