Have you ever face this error -
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.
The reason why Vue doesn’t recommend to modify the
prop data because if the parent component has a different value, the data in the child component will be re-render.
How to solve it?
I’m gonna create a simple Vue component consist of input with
v-model attached to it and another Card component that accepts the
v-model data as a
props and displays it.
This is how the interface will looks alike.
This is how the interface works.
Every-time user type in the input, it will reflect directly in the card below. It’s because we’re passing
v-model: number as
prop in the
Any value that user’s typing will reflect immediately.
My next question is what’s going to happen if we’re going to manipulate the data in the child component, which is the
Surprisingly, this is what’s happening.
When we want to increase the value in the child component, Vue gives us an error message that this is not recommended way.
Why is it not recommend?
If the data v-model in the parent is changed, the data in the child component will re-render.
For example, I add any number in the input, and I increase the
number using the plus button. What happens if I add a new value in the
The value that we increased just now is getting a new value from the input.
How do we solve it?
Since we cannot modify the props data directly, so we need to replicate the
props data into a variable.
addNumber methods, assign the props into a new variable and do the calculation.
The next question is, how do we send the new number value to the parent? 🤔
Thank god, there is a custom event to solve it. We need to add the custom event in the
It’s mean that we’re sending a
myNumber data through
update-number event name. Since we’re sending a custom data, the parent component needs to listen to the
App.vue, add the listener to the
If there’s an
emit event called
update-number triggered in the child component,
update function will be called.
App.vue file, add the
update function in the
Remember, when we’re sending the custom event, we’re sending
myNumber as a parameter. So, in the
update function need to have one parameter to get the data.
After that, the new value we get from the custom event will be assigned to the
number data. Since, the child component data will be re-render if every time the
props data changed, we can see the instant update in the
Originally published at https://jakzaizzat.com