Craig van Tonder
Craig van Tonder

Reputation: 7687

Vuex - Computed property based on a modules state does not update on dispatch?

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

Answers (2)

Sajib Khan
Sajib Khan

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

T. Dirks
T. Dirks

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

Related Questions