5
votes

I'm creating a counter using Vue & Vuex 2.
When trying to access the count property on the store object, using this.$store.state.count, I get an Cannot read property 'state' of undefined error.

The error doesn't show up and everything works just fine when I'm creating the store instance inside main.js, instead of importing it.

main.js

import Vue from 'vue'
import Vuex from 'Vuex'
import App from './App.vue'
import store from './store'

new Vue({
  el: '#app',
  store,
  render: h => h(App)
})

store.js

import Vue from 'Vue'
import Vuex from 'Vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count: 1
  }
});

Counter.vue

export default {
  name: 'counter',
  template: `<span>{{ count }}</span>`,
  computed: {
    count () {
        return this.$store.state.count
    }
  },
}

Any idea what's wrong with the store import?

1

1 Answers

6
votes

You have imported vue differently:

import Vue from 'Vue'

within store.js and

import Vue from 'vue'

within main.js

change your store.js import to match main.js to fix the issue, i.e.

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

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count: 1
  }
});

you can also remove the Vuex import in main.js