0

I keep getting this error in browser Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "dataElements"

I have @Prop() private dataElements: any[]; in my component. This prop is changed by the parent and by the child, also it might need a watcher to do some operations when it is changed.

How can i create a computed property out of it?

Marko Taht
  • 1,448
  • 1
  • 20
  • 40
  • Possible duplicate of [Avoid mutating a prop directly](https://stackoverflow.com/questions/56752919/avoid-mutating-a-prop-directly) – Rich Jun 25 '19 at 11:42
  • @Rich kinda is and kinda isnt. Im using Typescript so i cant use the solution offered there. I need a solution in Typescript not in Javascript. I-d do the conversion myself, but i dont know Vue well enoguh for it. – Marko Taht Jun 25 '19 at 12:52

1 Answers1

0

As of for Vue you should never have to mutate a prop (which has been passed to a child component through the parent), because whatever you do within the child component - the parent can always change and overwrite the props value (as already stated in the error message).

To mutate a passed in prop you have to define a locally used one in your child component. In your case this can be done by a computed property which just returns a newly created array depending on your prop.

computed: {
    elements() {
        return [...this.dataElements]
    }
}

Any change on the array should always be reported to the parent, by emitting an event, which at the end will handle the appropriate mutation and pass the prop back again to the child.

Aer0
  • 3,792
  • 17
  • 33
  • Im not actually modifying the props. I only have a initilizer for it in constructor. Other than that i just read the prop. This error is so annoying. I either get error that it is not initilized or i get error that im mutating it. There is no pleasing the compiler. – Marko Taht Jun 26 '19 at 06:20
  • Would you mind sharing your exact line of code? While initializing something in the constructor - Do you mutate the prop? Even that shouldn't be done, due to Vues reactivity system. – Aer0 Jun 26 '19 at 06:26
  • constructor() { super(); this.dataElements = []; } – Marko Taht Jun 26 '19 at 06:42