解决报错:Avoid mutating a prop directly since the value will be overwritten whenever the parent componen

一、问题描述

在父组件中引用子组件,使用时页面报错:

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: "addGroup"

百度翻译:

避免直接更改道具,因为每当父组件重新渲染时,该值都会被覆盖。相反,使用基于道具值的数据或计算属性。正在变异的道具:“addGroup”

二、出现问题原因

以本问题为例:prop在子组件接收父组件传递过来的参数“addGroup”,但是在子组件中修改了这个参数 “addGroup”

三、解决办法

1、在data中定义一个变量,赋值为这个参数。但是这样的话参数 “addGroup”只会在该子组件被创建时赋值一次。

eg:注意:新声明的变量名要区别于父组件传来的参数名,在子组件的代码(methods/html)中使用新声明的变量名

 2、若要实现子组件中的参数和父组件中的动态关联, 可以在watch属性中监听这个参数 “addGroup”,为其赋值,实现动态关联。

猜你喜欢

转载自blog.csdn.net/qq_45991812/article/details/131121538