简体   繁体   中英

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?

You should change state.main++ to state.current++

 const mutations = { INCREMENT_CURRENT_COUNT (state) { // change state.main -> state.current state.current++ } } 

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++

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM