Change count value in Vuex store of Vue app using v-model
P粉882357979
P粉882357979 2024-03-22 00:31:42
0
1
423

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粉882357979
P粉882357979

reply all(1)
P粉958986070

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)
    }
  }
})
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!