搜索

首页  >  问答  >  正文

使用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 天前459

全部回复(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
  • 取消回复