Reputation: 7687
I am exploring the module documentation for Vuex and have been stuck for quite a while now with updating a value within a modules state from the component which uses it. Here is what I have so far:
app/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import Counter from './modules/Counter'
Vue.use(Vuex)
export default new Vuex.Store({
modules: { Counter }
})
app/store/modules/Counter.js
const state = {
current: 0
}
const mutations = {
INCREMENT_CURRENT_COUNT (state) {
state.main++
}
}
const actions = {
increment ({ commit }) {
commit('INCREMENT_CURRENT_COUNT')
}
}
export default {
namespaced: true,
state,
mutations,
actions
}
app/components/Test.vue
<template>
<div id="wrapper">
<p>{{ count }}</p>
<button @click="something()">Do something</button>
<button @click="add()">Add to count</button>
</div>
</template>
<script>
import { mapState, mapActions } from 'vuex'
export default {
computed: mapState({
count: state => state.Counter.current
}),
methods: {
something () {
alert('hello')
},
...mapActions('Counter', {
add: 'increment'
}),
}
}
</script>
Essentially, all I am trying to do is increment the current
value in the Counter
module when clicking the button in the component which fires the add()
method, it is what I might expect given the above but what actually happens is nothing.
So no error and the count
value within the vue component remains at 0.
Any ideas on what what am I doing wrong here?
Upvotes: 1
Views: 629
Reputation: 24194
You should change state.main++
to state.current++
const mutations = {
INCREMENT_CURRENT_COUNT (state) {
// change state.main -> state.current
state.current++
}
}
Upvotes: 2
Reputation: 3676
The problem isn't with the click handler or the action, it's in the mutation.
In your mutation INCREMENT_CURRENT_COUNT
you have this:
INCREMENT_CURRENT_COUNT (state) {
state.main++
}
Whilst your state only has a property called current
.
In order to make it work, change:
state.main++
To:
state.current++
Upvotes: 0