(復習)父子組件傳值使用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賦值給新變量)

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>      


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM