簡體   English   中英

Vuex-基於模塊狀態的計算屬性不會在派發時更新嗎?

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

我正在探索Vuex的模塊文檔,並且由於使用它的組件更新模塊狀態中的值而已經停滯了一段時間。 這是我到目前為止的內容:

應用/存儲/ 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 }
})

應用程序/商店/模塊/ 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
}

應用/組件/ 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。

關於我在做什么錯的任何想法?

您應該將state.main++更改為state.current++

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

問題不在於單擊處理程序或操作,而在於突變。 在您的突變INCREMENT_CURRENT_COUNT您有以下內容:

INCREMENT_CURRENT_COUNT (state) {
    state.main++
}

雖然您的州只有一個稱為current的屬性。

為了使它起作用,請更改:

state.main++

至:

state.current++

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM