【问题标题】:Updating object in array with Vuex [duplicate]使用Vuex更新数组中的对象[重复]
【发布时间】:2018-05-19 06:11:09
【问题描述】:

如何使用 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'});
  })
}

【问题讨论】:

  • 怎么了?你有什么错误?
  • vue 中的反应性与您所期望的不同。在状态对象中预先创建属性或使用 Vue.set 函数 - vuejs.org/v2/api/#Vue-set
  • Vuex Mutations 和 Actions 只能接收两个参数,查看文档vuex.vuejs.org/en/mutations.html
  • 使用 vuex 更新数组中对象的任何方法?直接使用 axios 很好,但我对状态管理很满意。

标签: javascript vue.js vuejs2 vuex


【解决方案1】:
[mutationType.UPDATE_CATEGORY] (state, id, category) {
  state.categories = [
     ...state.categories.filter(element => element.id !== id),
     category
  ]
}

这是通过将“类别”数组替换为没有匹配元素的原始数组,然后将更新后的元素连接到数组的末尾来实现的。

此方法的一个警告是它破坏了数组的顺序,尽管在很多情况下这不会成为问题。只是需要记住的一点。

【讨论】:

  • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
  • 它将现有的 state.categories 替换为包含旧类别对象但没有更新类别对象的新数组,并将新类别对象附加到它。
  • @Davіd 要回答您的问题,上述代码有效的原因是更改检测发生在数组引用更改时。任何使用数组方法的操作都会触发更改检测Vuejs.org 同样添加或删除项目也需要数组引用更新例如:state.myArray[2] = {id: "112", name: "ABC"} state.myArray = [。 ..state.myArray] Ref
  • 这是在不破坏数组顺序的情况下做到这一点state. categories = [...state. categories.map(item => item.id !== updatedItem.id ? item : {...item, ...updatedItem})]
  • 创建一个全新的数组(没有更新对象)然后将一个新对象附加到该数组与使用查找索引并调用splice相比有什么优势?
猜你喜欢
  • 2019-04-10
  • 1970-01-01
  • 2015-05-12
  • 1970-01-01
  • 1970-01-01
  • 2019-09-10
  • 1970-01-01
  • 1970-01-01
  • 2021-12-21
相关资源
最近更新 更多