Reputation: 601
I am learning vuejs but I can't find a proper answer. When i am clicking on edit age button or change my name button i am getting below error.
[Vue warn]: 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: "myName"
[Vue warn]: 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: "userAge"
Code is here.
https://codesandbox.io/s/k2197nr4o3
Please let me know what is wrong in this code.
Upvotes: 3
Views: 11411
Reputation: 27729
It is obvious that you are trying to change directly the props properties.
For example:
props: { name: 'something' }
methods: {
change_name(new_name) {
this.name = new_name
}
}
This is not recommended and it may lead on reactivity lack.
As solution, you can use parent child communication. So whenever you want to change a prop, just emit an event to the parent component. So the above example should be:
props: { name: 'something' }
methods: {
change_name(new_name) {
this.$emit('name-updated', new_name)
}
}
And on the parent component listen to that event to change the prop you are passing:
<child-component :name="name" @name-updated="name = $event" />
Or my favorite way is to use .sync modifier.So the parent component should be:
<child-component :name.sync="name" />
and the method on the child component:
change_name(new_name) {
this.$emit('update:name', new_name)
}
If the components do not have parent-child relation take a look to Vue.js Event Bus or Vuex
Upvotes: 11
Reputation: 1381
Use a computed value instead. For example in your UserEdit.vue:
In your template:
<p>User Age: {{ computedUserAge }}</p>
In your script:
methods: {
editAge() {
this.computedUserAge = 30;
}
},
computed: {
computedUserAge: {
get() {
return this.userAge;
},
set(v) {
this.$emit("ageWasEdited", v);
}
}
}
Upvotes: 1