Update Data Using Vuex
As Vuex, I'm trying to update an object using form. My code like this. In store: const state = { categories: [] }; //mutations: [mutationType.UPDATE_CATEGORY] (state, id, categ
Solution 1:
You can wrap your parameters in 1 payload
object:
In your component
this.$store.dispatch('updateCategory', {
id: this.$route.params.id,
data: this.category
});
in your store, you need to made new object when edit categories
array (you can read more about immutable)
const state = {
categories: []
};
//mutations:
[mutationType.UPDATE_CATEGORY] (state, payload) {
state.categories = state.categories.map(category => {
if (category.id === payload.id) {
returnObject.assign({}, category, payload.data)
}
return category
})
}
//actions:updateCategory({commit}, payload) {
categoriesApi.updateCategory(payload.id, payload.data).then((response) => {
commit(mutationType.UPDATE_CATEGORY, payload);
router.push({name: 'categories'});
})
}
Solution 2:
and much more simple, just use methods to modify arrays (never modify them directly) (check this: https://vuejs.org/2016/02/06/common-gotchas/#Why-isn%E2%80%99t-the-DOM-updating even old and DOM related, is still valid)
So just find your object and replace with splice in your mutation:
const index = state.objectsArray.map(o => o.id).indexOf(newObject.id);
state.objectsArray.splice(index, 1, newObject);
Solution 3:
ES6
way of updating
//mutations UPDATE:
[mutationType.UPDATE_CATEGORY] (state, payload) {
state.categories = [
...state.categories.map(item =>
item.id !== updatedItem.id ? item : {...item, ...updatedItem}
)
]
}
//mutations CREATE:
[mutationType.CREATE_CATEGORY] (state, category) {
state.categories = [category, ...state.categories] //Append to start of array
}
//mutations DELETE:
[mutationType.DELETE_CATEGORY] (state, id) {
state.categories = [
...state.categories.filter((item) => item.id !== id)
];
}
Solution 4:
You just need one line code because the javascript object has reference capabilities
//mutations:[mutationType.UPDATE_CATEGORY] (state, id, category) {
Object.assign(state.categories.find(element => element.id === id), category);
}
Post a Comment for "Update Data Using Vuex"