Heim  >  Fragen und Antworten  >  Hauptteil

Ändern Sie den Zählwert im Vuex-Store der Vue-App mithilfe des V-Modells

Dieser Code generiert keinen Fehler, aber wenn ich die Zählung ändere, wird das Ergebnis nicht auf dem Bildschirm angezeigt. Bitte helfen Sie mir, dieses Problem zu lösen.

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粉882357979211 Tage vor425

Antworte allen(1)Ich werde antworten

  • 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)
        }
      }
    })

    Antwort
    0
  • StornierenAntwort