使用v-model在Vue应用的Vuex存储中更改计数值
P粉882357979
P粉882357979 2024-03-22 00:31:42
0
1
473

此代码不会生成错误,但当我更改计数时,它不会在屏幕上显示结果。请帮我解决这个问题。

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

全部回复(1)
P粉958986070

首先,您不需要 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)
    }
  }
})
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板