Is it possible to iterate over Vuex data in a Vue file, identify the data that needs updating, and then pass that data to an action for committing, with the mutation handling the update?
I'm uncertain because standard Vuex mutations require a 'state' parameter, so I wonder if all the looping should be done within the mutation or if passing indexes would be more efficient for finding specific fields to change.
Here is a code example for reference:
someVueFile.vue
computed: {
...mapState({
arrayOfObjects: (state) => state.someVuexStore.arrayOfObjects
}),
},
methods: {
myUpdateMethod() {
let toBeUpdated = null;
let newValue = "oneValue";
this.arrayOfObjects.forEach((myObject) => {
if (myObject.someDataField !== "oneValue") {
toBeUpdated = myObject.someDataField;
}
})
if (toBeUpdated) {
let updatedObject = {
updateThis: toBeUpdated,
newValue: newValue
}
this.$store.dispatch("updateMyObjectField", updatedObject)
}
}
}
someVuexStore.js
const state = {
arrayOfObjects: [],
/* contains some object such as:
myCoolObject: {
someDataField: "otherValue"
}
*/
}
const mutations = {
updateMyObjectField(state, data) {
data.updateThis = data.newValue;
}
}
const actions = {
updateMyObjectField(state, data) {
state.commit("updateMyObjectField", data);
}
}