使用 Vuex 更新数组中的对象 [英] Updating object in array with Vuex

查看:90
本文介绍了使用 Vuex 更新数组中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 Vuex 更新数组内的对象?我试过了,但没有用:

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'});
  })
}

推荐答案

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

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

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.

这篇关于使用 Vuex 更新数组中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆