Asked By: Anonymous
Hi I made a boolean value in parent component, and passed it to the child component as a props. it has initialized as false, and after the user view the component, the value will change to true, which means the page has been visited.
I have done some research and followed How to properly pass data from child to parent and parent to child component?
here is my js code:
<script>
export default {
props: {
hasLoad: {
type: Boolean
}
},
data () {
return {
hasLoadModel: this.hasLoad
}
},
created: function() {
console.log(this.hasLoad);
},
beforeDestroy: function() {
this.hasLoadModel = true;
this.hasLoad = true;
console.log(this.hasLoadModel);
console.log(this.hasLoad);
}
}
</script>
and html code
<div v-model="skillLoadModel">..</div>
But I still get
[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.
I have tried to change the value at either of beforeDestroy or Destroyed, or do not use v-model, but none of them works. The value has changed after I left the page, but when I reenter the page, the value has reset to default value.
Can someone help me please?
Thanks
Solution
Answered By: Anonymous
Don’t change the value of the prop. Have the component emit an event so that the parent can take the appropriate action.
Below is an example of a component that is created when the checkbox is checked, and is destroyed when it gets unchecked. The component emits a “dying” event, and the parent receives it and prints a scream to the console.
new Vue({_x000D_
el: '#app',_x000D_
data: {_x000D_
showIt: true_x000D_
},_x000D_
methods: {_x000D_
scream() {_x000D_
console.log("Aaarg!");_x000D_
}_x000D_
},_x000D_
components: {_x000D_
myComponent: {_x000D_
beforeDestroy: function() {_x000D_
this.$emit('dying');_x000D_
}_x000D_
}_x000D_
}_x000D_
});
_x000D_
<a href="//unpkg.com/[email protected]/dist/vue.js">//unpkg.com/[email protected]/dist/vue.js</a>_x000D_
<div id="app">_x000D_
<input type="checkbox" v-model="showIt">_x000D_
<my-component v-if="showIt" hasload="true" @dying="scream" inline-template>_x000D_
<div>Here I am</div>_x000D_
</my-component>_x000D_
</div>
_x000D_
_x000D_
x000D