Home > Mobile >  vue.js code modularity question to prevent a prop mutation inside a child component
vue.js code modularity question to prevent a prop mutation inside a child component

Time:07-15

Spent quite some time trying to deal with an unexpected mutation prop in a child component until I stumbled upon this magnificient quote :

When you have a component that receives an object through a prop, the parent is the one controlling that object, if you update it inside the child you break the synchronization of the state

I then realized that my code was all but modular and needed refactoring to speed up future developement.

My (simple) project consists of an app.vue containing a v-data-table and a button that opens a dialog to add a new entry. Everything is connected to a database and queries/commands done via Axios. As of now, everything was in a single file. I succeded on transfering my crud commands (and another fct) in another component file named methods.js. So far so good (i hope) but things get more complicated with the dialog for new entries... I have v-model(s) in v-text-fiels (in methodes.js) bound to the new object attributes (still in the main as of now) and is obviously not happy, spitting :

error Unexpected mutation of "newException" prop

My question is then: What is the best practice in regard to clean-code / code modularity? Should I simply but the new object within the new dialog.vue? instead of the app.vue? Even more than that, should every components be in their own "component".js instead of a single one?

Thank you for the enlightment <3

CodePudding user response:

Every component should be inside its own "component".js and the components should be as simple as possible. The more components - the better. If you keep everything in a single file - you are doing yourself a very bad favor.

In order to avoid the mutation of an Object - you should either send (as props) only the data that is needed by the child component, or the child should emit events when it wants to mutate the Object and then the parent can listen for these events and mutate the Object itself.

  • Related