Reputation: 117
I'm struggling for a couple of hours with vuex. It's the first time I use it and even though I follow the documentation something is not working but I really can't figure it out.
So I have the first example of the vuex doc that doesn't work.
I have a count
computed value that return the store state.
It's display on the page. The started value is 0 and the view is displaying 0. But hitting the buttons doesn't change the display.
If I put directly the store into the App.js in a constant, no problem it works.
I know I'm missing something...
homeStore.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
},
decrement (state) {
state.count--
}
}
})
App.js
import store from '../store/homeStore'
new Vue({
el: '#app',
store,
computed: {
count () {
return store.state.count
},
},
methods: {
increment () {
store.commit('increment')
},
decrement () {
store.commit('decrement')
}
}
})
Upvotes: 1
Views: 180
Reputation: 401
Make use of Vuex store actions
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: { count: 0 },
mutations: {
increment (state) {
state.count++
},
decrement (state) {
state.count--
}
},
actions: {
increase ({ commit }) {
commit('increment')
},
decrease ({ commit }) {
commit('decrement')
}
}
})
access the action method using this.$store.dispatch('increase') to increment the count and vice versa for decrement
Upvotes: 1
Reputation: 3289
If you try to console.log(store)
, it will returns undefined.
The right way to access the store is to use this.$store
(should be a component).
By providing the store option to the root instance, the store will be injected into all child components of the root and will be available on them as this.$store.
Therefore, your updated code should be:
methods: {
increment () {
this.$store.commit('increment')
},
decrement () {
this.$store.commit('decrement')
}
}
Upvotes: 0