如何使用 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'});
})
}
[mutationType.UPDATE_CATEGORY] (state, id, category) {
state.categories = [
...state.categories.filter(element => element.id !== id),
category
]
}
这是通过将“categories”数组替换为没有匹配元素的原始数组,然后将更新后的元素连接到数组的末尾来实现的。
此方法的一个警告是它会破坏数组的顺序,尽管在很多情况下这不会成为问题。只是要记住一些事情。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)