Home  >  Q&A  >  body text

Change count value in Vuex store of Vue app using v-model

This code does not generate an error but when I change the count it does not display the results on the screen. Please help me solve this problem.

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 days ago428

reply all(1)I'll reply

  • P粉958986070

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

    First of all, you don't need v-model to update your store. You can create local copies and update them instantly.

    Second thing, I don't think you want to update the entire count of every object, but I think you want to update one item in particular.

    This is what I'm going to do:

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

    reply
    0
  • Cancelreply