Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't access $store when importing Vuex instance from an external file

Tags:

vue.js

vuex

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?

like image 525
Guy Avatar asked Nov 18 '16 11:11

Guy


1 Answers

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

like image 149
GuyC Avatar answered Sep 18 '22 19:09

GuyC