I have a Vue 2 application with a state variable (an array of box objects) called boxes
. I have a computed property which extracts a subset of these boxes (nearest_box_linked_boxes
).
I have a method which iterates through the boxes returned by nearest_box_linked_boxes
, and changes the value of a property in each element:
for(let i=0;i<this.nearest_box_linked_boxes.length;i )
{
let box = this.nearest_box_linked_boxes[i];
box.object_class = this.$store.state.selected_object_class;
box.patch();
}
This method is returning an error:
vue.esm.js:648 [Vue warn]: Error in v-on handler: "TypeError: Cannot assign to read only property 'object_class' of object '#<Box>'"
I never explicitly made any of the box objects (or their properties) read-only. I do understand that I can't write to nearest_box_linked_boxes
(the parent array object) because it's a calculated property, but I thought it should be possible to modify properties of each element in this array.
Am I running into an issue caused by Vue and calculated properties here, or something else?
CodePudding user response:
You should always treat computed properties as “read-only”, the exception being computed setters.
While its technically possible to mutate an object returned by a computed properties, it’s generally bad idea. The object will be replaced as soon as a dependency changes, and your changes would be lost.
CodePudding user response:
This turned out to be my own mistake. Nikola's response is probably good practice, but I was actually calling Object.freeze at some point in my code and I had forgotten about it. This was not a side-effect of anything related to Vue or anything really mysterious at all.