Vuejs Mutating Object Passed As A Prop
Solution 1:
Is mutating a prop bad practice?
Yes absolutely. In more complex applications it is very easy to lose track of where/what/why is mutated
What is the right way to handle state across different components?
In small projects you can really do whatever you want, because you will most likely be able to follow the logic - even after not looking at the project for a year. The possibilities include:
- Mutating Props (ugly but will work)
- Using Events to mutate state in parent components; take a look at the EventBus (better)
- Use global shared state; look at Vuex (best, but a little more boilerplate)
In big projects, however, you should absolutely use Vuex. It is a module for Vue that adds global shared state to your app, which you can access and mutate from all places in your app.
Solution 2:
I think I understand what you are trying to do, You want to pass data to a child component, mutate it and then give that data back to the parent component.
You never want to mutate the props data given to the child component, however you CAN mutate a local state of the data, which could be an exact clone of the prop.
You can do this in many ways, I normally use a computed property as suggested in the Vue documentation: https://vuejs.org/v2/guide/components-props.html
in the computed return, just return the data coming in from the property.
Post a Comment for "Vuejs Mutating Object Passed As A Prop"