NuxtJS store state variables keeps returning undefined

1.6k Views Asked by At

I have a problem with the NuxtJs store it always returns undefined I found a lot of similar questions but none has fixed the problem. here's my code:

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

Vue.use(Vuex)

const store = new Vuex.Store({
    state(){ 
        return{
            count: 500
        }
    },
    getters: {
        getCount: (state) => {
            state.count
        }
    },
})

then I tried getting it this way

this.$store.getters.getCount

also tried this

computed: {
        ...mapGetters(['getCount'])
},
created(){
        console.log("count: "+this['getCount'])
}

here's the error: enter image description here

1

There are 1 best solutions below

1
tony19 On BEST ANSWER

Nuxt sets up a store automatically for you, so you don't need to instantiate your own store.

Remove the setup code:

// REMOVE ALL THIS:
//
// import Vue from 'vue'
// import Vuex from 'vuex'
//
// Vue.use(Vuex)
//
// const store = new Vuex.Store({/*...*/})

And create store/index.js with the following contents:

export const state = () => ({
  count: 500,
})

export const getters = {
  getCount: state => state.count,
}

Now, you can access the store in your components:

export default {
  mounted() {
    console.log('count', this.$store.getters.getCount)
  }
}

demo