Use data or a computed property based on the prop value instead. Vue JS
Well, I'm trying to change the value of "variable" in Vue, but when I click on the button, they throw a message in the console:
[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 value. Prop being mutated: "menuOpen"
I don't know how to solve this problem ...
My file.vue:
<template>
<button v-on:click="changeValue()">ALTERAR</button>
</template>
<script>
export default {
name: 'layout',
props: [ 'menuOpen' ],
methods: {
changeValue: function () {
this.menuOpen = !this.menuOpen
}
},
}
</script>
Can anyone help me? Thanks to
source to share
The warning is pretty clear. In your method, changeValue
you change the value of the property menuOpen
. This will change the value inside the component, but if the parent component needs to redraw for any reason, then any value inside the component will be overwritten by the current state outside the component.
Typically you handle this by making a copy of the value internally.
export default {
name: 'layout',
props: [ 'menuOpen' ],
data(){
return {
isOpen: this.menuOpen
}
},
methods: {
changeValue: function () {
this.isOpen= !this.isOpen
}
},
}
If you need to communicate a value change back to the parent, then you must $emit
change.
changeValue: function () {
this.isOpen= !this.isOpen
this.$emit('menu-open', this.isOpen)
}
source to share