【发布时间】:2018-11-19 12:21:11
【问题描述】:
我正在探索 Vuex 的模块文档,并且已经卡住了很长一段时间,因为我从使用它的组件更新模块状态中的值。这是我目前所拥有的:
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>
本质上,我要做的就是在单击触发add() 方法的组件中的按钮时增加Counter 模块中的current 值,这是我在上面所期望的,但是实际发生什么都没有。
所以没有错误,vue 组件中的count 值保持为0。
关于我在这里做错了什么有什么想法吗?
【问题讨论】:
-
你能在 Codesandbox 上复制这个问题吗?它会让调试和理解变得更容易。
-
@Phiter 感谢您的意见。 codesandbox.io/s/415j60717 并且它有效(facepalm)。正如我在对答案的评论中解释的那样,我的用例和问题有点复杂。
-
该死的,当我阅读问题时我什至没有注意到这一点
标签: javascript vuejs2 vuex