Home  >  Q&A  >  body text

Why are object properties marked read-only in my JavaScript (Vue) code?

<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粉464208937P粉464208937441 days ago536

reply all(1)I'll reply

  • P粉754477325

    P粉7544773252023-08-27 09:49:53

    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.

    reply
    0
  • Cancelreply