Update entire object in an array of objects in Vuex store with Vue.set()?

Viewed 2301

I have a form that needs to reactively update an entire object in an array of objects in a state mutation. I know Vue.set() works well for updating a single property, but I'm curious if it works to just update the full object. Something like this:

Vue.set(state.objects, obj.id, newObject)

The use case would be for a form update where the properties that are modified would be inconsistent. I may also just be misunderstanding Vue.set() altogether. The docs are extremely brief on this, saying only:

When adding new properties to an Object, you should either:

Use Vue.set(obj, 'newProp', 123), or

Replace that Object with a fresh one. For example, using the object spread syntax we can write it like this:

state.obj = { ...state.obj, newProp: 123 }

Any advice on the best way to go about this would be greatly appreciated!

I was previously updating the object by finding the index and replacing it, but that seemed to lack reactivity. Example:

let index = state.objects.findIndex(o => o.id === obj.id)
if (index !== -1) {
  state.objects[index] = new Object(obj)
  return
}
state.objects.push(new Object(obj))
0 Answers
Related