I'm having an issue using $emit in VueJS. I received this 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: "userAge"
Parent:
<template>
<div class="component">
<h1>The User Component</h1>
<p>I'm an awesome User!</p>
<button @click="changeName">Change my name</button>
<p>Name is {{ name }}</p>
<hr>
<div class="row">
<div class="col-xs-12 col-sm-6">
<app-user-detail
:myName="name"
:resetNameParent="resetNameFn"
@nameWasReset="name = $event"
:userAge="age"
></app-user-detail>
</div>
<div class="col-xs-12 col-sm-6">
<app-user-edit
:userAge="age"
@ageWasEdited="age = $event"
></app-user-edit>
</div>
</div>
</div>
</template>
<script>
import UserDetail from './UserDetail.vue';
import UserEdit from './UserEdit.vue';
export default {
data() {
return {
name: 'Max',
age: 27
}
},
methods: {
changeName() {
this.name = 'Anna'
},
resetNameFn() {
this.name = 'Max';
},
},
components: {
appUserDetail: UserDetail,
appUserEdit: UserEdit
}
}
</script>
<style scoped>
div {
background-color: lightblue;
}
</style>
Child:
<template>
<div class="component">
<h3>You may edit the User here</h3>
<p>Edit me!</p>
<p>User Age: {{ userAge }}</p>
<button @click="editAge">Edit Age</button>
</div>
</template>
<script>
export default {
props: ['userAge'],
methods: {
editAge() {
// this.userAge = 30; - przestarzaĆe
// this.$emit('ageWasEdited', this.userAge); - przestarzaĆe
this.$emit('ageWasEdited', 30);
}
}
}
</script>
<style scoped>
div {
background-color: lightgreen;
}
</style>
I read the manual but I could not implement the solution correctly.
How can I avoid this error?
this.userAge = 30, is commented out, but would definitely result in that error. Is that the problematic line of code? Or are you saying you're seeing the error with the code you've shared as written? - thanksd