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"数组替换为没有匹配元素的原始数组,然后将更新的元素连接到数组的末尾来实现.
这种方法的一个警告是它破坏了数组的顺序,尽管在很多情况下这不会是一个问题.请记住一些事情.