javascript 使用 Vuex 更新数组中的对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50422357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Updating object in array with Vuex
提问by Phuong Thuan
How can I update an object inside an array with Vuex? I tried this, but it didn't work:
如何使用 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'});
})
}
回答by ArtemSky
[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.
这是通过用没有匹配元素的原始数组替换 'categories' 数组,然后将更新的元素连接到数组的末尾来实现的。
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.
这种方法的一个警告是它破坏了数组的顺序,尽管在很多情况下不会有问题。只是要记住一些事情。

