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

有志者,事竟成,破釜沉舟,百二秦关终属楚; 苦心人,天不负,卧薪尝胆,三千越甲可吞吴。
原文地址:https://www.cnblogs.com/luyj00436/p/14871866.html