Updating object in array with Vuex [duplicate]

强颜欢笑 提交于 2020-04-10 07:54:30

问题


How can I update an object inside an array with Vuex? I tried this, but it didn't work:

const state = {
  categories: []
};

// mutations:
[mutationType.UPDATE_CATEGORY] (state, id, category) {
  const record = state.categories.find(element => element.id === id);
  state.categories[record] = category;
}

// actions:
updateCategory({commit}, id, category) {
  categoriesApi.updateCategory(id, category).then((response) => {
    commit(mutationType.UPDATE_CATEGORY, id, response);
    router.push({name: 'categories'});
  })
}

回答1:


[mutationType.UPDATE_CATEGORY] (state, id, category) {
  state.categories = [
     ...state.categories.filter(element => element.id !== id),
     category
  ]
}

This works by replacing the 'categories' array with the original array without the matching element, and then concatenating the updated element to the end of the array.

One caveat to this method is that it destroys the order of the array, although in a lot of cases that won't be a problem. Just something to keep in mind.



来源:https://stackoverflow.com/questions/50422357/updating-object-in-array-with-vuex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!