搜尋

首頁  >  問答  >  主體

使用v-model在Vue應用的Vuex儲存中更改計數值

此程式碼不會產生錯誤,但當我更改計數時,它不會在螢幕上顯示結果。請幫我解決這個問題。

import Vue from 'vue'
    import Vuex from 'vuex'
    
    Vue.use(Vuex)
    
    export default new Vuex.Store({
      state: {
        lists: [ 
          {
            title: "User",
            count: 15,
          },
          {
            title: "Admin",
            count: 41,
          },
          {
            title: "Total Members",
            count: 100,
          },
          {
            title: "Manager",
            count: 35,
          }
        ]
      },
      mutations: {
        updateMessage (state, count) {
          state.lists.count = count
        }
      },
      actions: {
      },
      modules: {
      }
    })

P粉882357979P粉882357979246 天前461

全部回覆(1)我來回復

  • P粉958986070

    P粉9589860702024-03-22 19:43:14

    首先,您不需要 v-model 來更新您的商店。您可以建立本機副本並即時更新。

    第二件事,我認為您不想更新每個物件的全部計數,但我想您想特別更新一個項目。

    這就是我要做的:

    // 1. In component you watch state.lists and copy it immediately on init, deeply & on change:
    
    data() {
      return {
        localCopyOfLists: []
      }
    },
    watch: {
      state.lists: {
        immediate: true,
        deep: true,
        handler(v) {
          this.localCopyOfLists = this.state.lists.map(x => (x))
        }
      }
    }
    
    // 2. Methods to change count of element in local list.
    
    methods: {
      updateItemInArray(index, count) {
        this.localCopyOfLists[index].count = count
        this.store.dispatch('SAVE_NEW_ARRAY', this.localCopyOfLists)
      }
    }
    
    // 3. You update your store.
    
    import Vue from 'vue'
    
    export default new Vuex.Store({
      actions: {
        SAVE_NEW_ARRAY ({commit}, payload) {
          commit('UPDATE_ARRAY', payload)
        }
      },
      mutations: {
        UPDATE_ARRAY (state, payload) {
          Vue.set(state, lists, payload)
        }
      }
    })

    回覆
    0
  • 取消回覆