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
Related videos on Youtube
Author by
steve
Updated on June 25, 2022Comments
-
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 over 7 yearsThe error does not mean that
$store
is not defined. Read carefully. It says thatthis
is not defined.
-
-
steve over 7 yearsThanks. But I just want to get state, not set.
-
joaumg over 7 yearsEdited, to reflect the get part (;
-
Dave Stein about 7 yearsI 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 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...