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

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

作者:互联网

报错: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赋值给新变量)

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4   <meta charset="UTF-8">
 5   <meta name="viewport" content="width=device-width, initial-scale=1.0">
 6   <meta http-equiv="X-UA-Compatible" content="ie=edge">
 7   <title>Document</title>
 8 </head>
 9 <body>
10 
11   <div id="app">
12     <h3>我是父组件</h3>
13     <templ :num-from-father="fatherData"
14     :num-from-father2="fatherData2"
15     @change1="changeFunc1"
16     @change2="changeFunc2"/>
17   </div>
18 
19   <template id="temp">
20     <div>
21       <h3>我是子组件</h3>
22       <p>props1:{{numFromFather}}</p>
23       <p>转存的值:{{receiveNum1}}</p>
24       <!-- 方法1  -->
25       <input type="number" :bind="receiveNum1" @input="receiveNum1Input">
26       <p>props2:{{numFromFather2}}</p>
27       <p>转存的值:{{receiveNum2}}</p>
28       <!-- 方法2 使用watch  -->
29       <input type="number" v-model="receiveNum2">
30     </div>
31   </template>
32   <script src="/js/vue.js"></script>
33   <script>
34     const vm = new Vue({
35       el:'#app',
36       data:{
37         fatherData:0,
38         fatherData2:10
39       },
40       methods: {
41         changeFunc1(value){
42           this.fatherData = value*1;
43         },
44         changeFunc2(value){
45           this.fatherData2 = value*1;
46         }
47       },
48       components:{
49         templ:{
50           template:'#temp',
51           props:{
52             numFromFather:Number,
53             numFromFather2:Number,
54           },
55           data(){
56             return{
57               receiveNum1:this.numFromFather,
58               receiveNum2:this.numFromFather2,
59             }
60           },
61           methods: {
62             receiveNum1Input(event){
63               this.receiveNum1 = event.target.value;
64               this.$emit('change1',this.receiveNum1);
65               this.receiveNum2 = this.receiveNum1*100;
66               this.$emit('change2',this.receiveNum2);
67             }
68           },
69           watch: {
70             receiveNum2(newValue){
71               this.receiveNum2 = newValue;
72               this.$emit('change2',this.receiveNum2);
73               this.receiveNum1 = this.receiveNum2/100;
74               this.$emit('change1',this.receiveNum1);
75             }
76           },
77         }
78       }
79     })
80   </script>
81 </body>
82 </html>

标签:Avoid,value,prop,receiveNum1,receiveNum2,报错,组件,event
来源: https://www.cnblogs.com/sweetC/p/12085375.html