【问题标题】:Vuex - Computed property based on a modules state does not update on dispatch?Vuex - 基于模块状态的计算属性不会在调度时更新?
【发布时间】: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


【解决方案1】:

您应该将state.main++ 更改为state.current++

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

【讨论】:

  • 该死的我没注意到
  • 很好,谢谢!话虽这么说,当我在代码沙盒上做一个例子时,我确实发现了这一点。对我来说,问题是我将它与电子结合使用,特别是vuex-electron,并没有注意到它说you need to create an instance of store in the main process的部分。解决了我的问题,尽管我知道它并没有真正包含在我的简单示例中(这个包还没有标签)。
【解决方案2】:

问题不在于点击处理程序或操作,而在于突变。 在你的突变INCREMENT_CURRENT_COUNT 你有这个:

INCREMENT_CURRENT_COUNT (state) {
    state.main++
}

虽然您所在的州只有一个名为 current 的属性。

为了让它工作,改变:

state.main++

收件人:

state.current++

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-09
    • 2018-01-06
    • 2019-10-19
    • 2019-07-13
    • 2019-07-14
    • 2020-08-11
    • 2021-04-16
    • 2021-07-09
    相关资源
    最近更新 更多