4

Vue allows to mutate props but it is not recommended. In the docs (https://vuejs.org/guide/components/props.html#one-way-data-flow) I found that

As a best practice, you should avoid such mutations [mutating nested props by the child] unless the parent and child are tightly coupled by design.

This sounds for me that it is not good practice to do so, but it is okay. However, in all forum posts I found, they say rather things like "don't ever do this!" and that re-rendering of the parent component can even corrupt the data (i.e. Vue 2 - Mutating props vue-warn).

If it was up to me, I would just stick to the recommendation and not argue about this. However, the team I work in uses prop mutation extensively.

So far it works, but I'm afraid that in future there might occur problems. Is there the risk that in future versions Vue could really forbid this? Or that they apply subtle changes that would be compatible only for code that follows the recommendation?

What I wonder is, how other people deal with situations where the changes are deep in the object. When this is done via emits, one needs a lot of emits also in all components in between.

It would be also interesting to know, how uncommon the practice with props mutation is. Does anybody of you do it the same way?

VeGoh5i
  • 51
  • 2

1 Answers1

2

There are 2 kinds of mutations - when you mutate a primitive value (String, Number, Boolean) and when you mutate an Object.

Mutating a primitive value prop inside the child will restore the original value coming from the parent as soon as the child is re-rendered.
How dangerous is this depends entirely on your usecase - Vue can only warn you "Dude, make sure you know what you are doing". Eventually in some of the next Vue versions they may replace the warning with an error - but even the maintainers do not know when and whether this can happen.

Mutating an Object is actually mutating its properties and since Objects are accessed by reference rather than value - all mutations from the child will persist and will affect the parent (which might not expect such side effects). Again it is entirely up to your usecase - but sometimes it's simply more convenient to mutate directly instead of signaling the parent by emitting events, especially if the mutated data is deeper in the Object.

The only risk for you is that you should monitor your application (and browser's console) to catch the moment when these warnings from Vue become errors.
The best course of action is to try convincing your colleagues to refactor the code and avoid these mutations as much as possible (you probably won't be able to get rid of all of them).

IVO GELOV
  • 13,496
  • 1
  • 17
  • 26