Why are object properties marked read-only in my JavaScript (Vue) code?
P粉464208937
P粉464208937 2023-08-26 22:18:27
0
1
563
<p>I have a Vue 2 application that has a state variable (an array containing box objects) called <code>boxes</code>. I have a computed property that extracts a subset of these boxes (<code>nearest_box_linked_boxes</code>). </p> <p>I have a method that loops through the boxes returned by <code>nearest_box_linked_boxes</code> and changes the value of an attribute on each element: </p> <pre class="brush:php;toolbar:false;">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(); }</pre> <p>This method returned an error: </p> <pre class="brush:php;toolbar:false;">vue.esm.js:648 [Vue warn]: Error in v-on handler: "TypeError: Cannot assign to read only property 'object_class' of object '#<Box>'"</pre> <p>I have never explicitly made any box objects (or their properties) read-only. I do know that I cannot write to <code>nearest_box_linked_boxes</code> (the parent array object) because it is a computed property, but I think it should be possible to modify the properties of each element in this array. </p> <p>Am I experiencing a problem caused by Vue and computed properties, or is it something else? </p>
P粉464208937
P粉464208937

reply all(1)
P粉754477325

You should always treat computed properties as "read-only", the exception is the computed property's setter.

While it is technically possible to modify the object returned by a computed property, this is generally a bad idea. Once a dependency changes, the object will be replaced and your changes will be lost.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template