Why is $store not defined?

19,584

Solution 1

You will never, ever edit the store directly.

You will ALWAYS trigger mutations.

As so (component.js):

<script>
import store from './vuex/store'

export default {
  name: 'landing-page',
  computed: {
    counter () {
      return store.state.count // get state
    }
  },
  created: () => {
    store.commit('increment') // set state
  }
}
</script>

Solution 2

That is because this in arrow function is not what you expect as this in "normal function". You can refer to Arrow functions or Javascript ES6 — Arrow Functions and Lexical this for more information

Share:
19,584

Related videos on Youtube

steve
Author by

steve

Updated on June 25, 2022

Comments

  • steve
    steve almost 2 years

    I am struggling to developed a project with vuejs and vuex, but it does not work with this.$store.state.count in the component. Why?

    My config:

    "vuex": "^2.0.0"
    

    store.js:

    import Vue from 'vue'
    import Vuex from 'vuex'
    Vue.use(Vuex)
    
    export default new Vuex.Store({
      state: {
        count: 12
      },
      mutations: {
        increment (state) {
          state.count++
        }
      },
      strict: true
    })
    

    main.js:

    import store from './vuex/store'
    import Vue from 'vue'
    
    new Vue({
      store,
      .
      .
      .
    }).$mount('#app')
    

    component.js:

    <script>
    export default {
        name: 'landing-page',
        created: () => {
          console.log('status2')
          console.log(this.$store.state.count)
        }
      }
    </script>
    

    Error:

    Uncaught TypeError: Cannot read property '$store' of undefined
    
    • Sebastian Simon
      Sebastian Simon over 7 years
      The error does not mean that $store is not defined. Read carefully. It says that this is not defined.
  • steve
    steve over 7 years
    Thanks. But I just want to get state, not set.
  • joaumg
    joaumg over 7 years
    Edited, to reflect the get part (;
  • Dave Stein
    Dave Stein about 7 years
    I don't understand this example as a Vue noob. Examples show me instantiating a store, and passing to Vue. When you import store in this example, are you importing an instantiated Vuex object then? Why wouldn't it be passed down in some way from Vue?
  • joaumg
    joaumg about 7 years
    @DaveStein "When you import store in this example, are you importing an instantiated Vuex object then?", Yes. You can also pass it in the Vue as mentioned here: vuex.vuejs.org/en/… to avoid relying on the global singleton...