uni-app 子組件不可修改父組件傳值(從陸議到陸遜)


首先,我們先看看在項目中的報錯。

 

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. Prop being mutated: “name”

子組件不可修改父組件的值。因此可以在data里定義一個值獲取父組件的值。當需要的時候,修改自定義的值即可。

故事背景

有一個可愛的孩子,父母給他取名為陸議。

因此,新建頁面parent.vue(父母),以及子組件son.vue(陸議)。parent.vue的主要代碼碼如下:

1 <template>
2     <view>
3         <son name="陸議"></son>
4     </view>
5 </template>
parent.vue

 經過深思熟慮,陸議想給自己改名字為陸遜。因此,son.vue代碼如下(PS:這里引用了一些樣式,因為與本文無關,不贅述):

 1 <template>
 2     <view class="flex flex-direction bg-white">
 3         <text class="margin text-xl">姓名:{{name}}</text>
 4         <button class="cu-btn bg-grey padding" @click="changeName">修改名字</button>
 5     </view>
 6 </template>
 7 
 8 <script>
 9     export default {
10         name:"son",
11         props:{
12             name:'',
13         },
14         data() {
15             return {
16                 
17             };
18         },
19         methods:{
20             changeName : function(){
21                 this.name = '陸遜';
22             }
23         }
24     }
25 </script>
son.vue

 點擊【修改名字】按鈕,改不了名字,報了以下錯誤。

 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. Prop being mutated: “name”

 一個“意思深長,才堪負重,觀其規慮,終可大任”的人,是一個是能改變世界的人,怎么可能給改變不了自己的名字?可是,問題出在哪里呢?

避免直接改變組件值,因為當父組件重新呈現時,這個值會被覆蓋。

因此,對於陸議來說,名字是父母起的,自己不能隨便改?那么沒有辦法了嗎?不,事情是權變的。可以根據父母起的名字,給自己起名“陸議”,然后再改為“陸遜”。改自己起的名字,沒問題吧?

子組件定義一個變量,獲取父組件的值,對外顯示和改變子組件的變量來代替父組件的值。

因此,子組件修改后的代碼如下?

 1 <template>
 2     <view class="flex flex-direction bg-white">
 3         <text class="margin text-xl">姓名:{{nowName}}</text>
 4         <button class="cu-btn bg-grey padding" @click="changeName">修改名字</button>
 5     </view>
 6 </template>
 7 
 8 <script>
 9     export default {
10         name:"son",
11         props:{
12             name:'',
13         },
14         data() {
15             return {
16                 nowName: this.name
17             };
18         },
19         methods:{
20             changeName : function(){
21                 this.nowName = '陸遜';
22             }
23         }
24     }
25 </script>
son.vue

 現在,點擊【修改名字】,可以“陸議”改為“陸遜”了。

參考網址

https://blog.csdn.net/weixin_38023551/article/details/83377542


免責聲明!

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



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