[英]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. 我正在探索Vuex的模块文档,并且由于使用它的组件更新模块状态中的值而已经停滞了一段时间。 Here is what I have so far: 这是我到目前为止的内容:
app/store/index.js 应用/存储/ 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 应用程序/商店/模块/ 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 应用/组件/ 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. 本质上,我想要做的就是单击触发add()
方法的组件中的按钮时,增加Counter
模块中的current
值,这是我期望的,但实际上没有任何反应。
So no error and the count
value within the vue component remains at 0. 因此没有错误,并且vue组件内的count
数值保持为0。
Any ideas on what what am I doing wrong here? 关于我在做什么错的任何想法?
You should change state.main++
to state.current++
您应该将state.main++
更改为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
您有以下内容:
INCREMENT_CURRENT_COUNT (state) {
state.main++
}
Whilst your state only has a property called current
. 虽然您的州只有一个称为current
的属性。
In order to make it work, change: 为了使它起作用,请更改:
state.main++
To: 至:
state.current++
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.