(复习)父子组件传值使用v-modal双向绑定,报错Avoid mutating a prop directly解决方案

时间:2021-04-21 22:03:21

报错:Avoid mutating a prop directly since the value will be overwritten whenever the parent component........

原因:所有的 prop 都使得其父子 prop 之间形成了一个单向下行绑定:父级 prop 的更新会向下流动到子组件中,但是反过来则不行。(父组件更新,子组件中的prop值也会更新,但子组件不能修改由父组件传递过来的值)

不能直接对父组件传来的值进行双向绑定,要先子组件里定义新的变量来接收父组件传来的值,接着我们可以使用v-modal+watch属性 或者 使用:binfd="" + @input=" func"(再定义这个func通过传入的event 得到改变的值,将event.target.value赋值给新变量)

   <div id="app">
<h3>我是父组件</h3>
<templ :num-from-father="fatherData"
:num-from-father2="fatherData2"
@change1="changeFunc1"
@change2="changeFunc2"/>
</div> <template id="temp">
<div>
<h3>我是子组件</h3>
<p>props1:{{numFromFather}}</p>
<p>转存的值:{{receiveNum1}}</p>
<!-- 方法1 -->
<input type="number" :bind="receiveNum1" @input="receiveNum1Input">
<p>props2:{{numFromFather2}}</p>
<p>转存的值:{{receiveNum2}}</p>
<!-- 方法2 使用watch -->
<input type="number" v-model="receiveNum2">
</div>
</template>
<script src="/js/vue.js"></script>
<script>
const vm = new Vue({
el:'#app',
data:{
fatherData:0,
fatherData2:10
},
methods: {
changeFunc1(value){
this.fatherData = value*1;
},
changeFunc2(value){
this.fatherData2 = value*1;
}
},
components:{
templ:{
template:'#temp',
props:{
numFromFather:Number,
numFromFather2:Number,
},
data(){
return{
receiveNum1:this.numFromFather,
receiveNum2:this.numFromFather2,
}
},
methods: {
receiveNum1Input(event){
this.receiveNum1 = event.target.value;
this.$emit('change1',this.receiveNum1);
this.receiveNum2 = this.receiveNum1*100;
this.$emit('change2',this.receiveNum2);
}
},
watch: {
receiveNum2(newValue){
this.receiveNum2 = newValue;
this.$emit('change2',this.receiveNum2);
this.receiveNum1 = this.receiveNum2/100;
this.$emit('change1',this.receiveNum1);
}
},
}
}
})
</script>