使用Vuex更新数组中的对象

Phu*_*uan 6 javascript vue.js vuex vuejs2

如何使用Vuex更新数组内的对象?我试过这个,但它不起作用:

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'});
  })
}
Run Code Online (Sandbox Code Playgroud)

Art*_*Sky 18

[mutationType.UPDATE_CATEGORY] (state, id, category) {
  state.categories = [
     ...state.categories.filter(element => element.id !== id),
     category
  ]
}
Run Code Online (Sandbox Code Playgroud)

这可以通过将"categories"数组替换为没有匹配元素的原始数组,然后将更新的元素连接到数组的末尾来实现.

这种方法的一个警告是它破坏了数组的顺序,尽管在很多情况下这不会是一个问题.请记住一些事情.

  • 这就是在不破坏数组状态顺序的情况下执行此操作的方法。类别 = [...状态。categories.map(item => item.id !== UpdatedItem.id ? item : {...item, ...updatedItem})]` (15认同)
  • 虽然此代码可以回答这个问题,但提供有关如何和/或解决问题的原因的其他背景将提高答案的长期价值. (5认同)
  • 创建一个全新的数组(没有更新对象)然后将一个新对象附加到该数组与使用查找索引并调用“splice”相比有什么优点? (2认同)