首页 > 解决方案 > 为什么更改子组件的属性会影响父组件?

问题描述

我的应用程序由一个具有组件的父应用程序组成。我的意图是隔离组件,以便父级(应用程序)和子级(组件)之间的唯一通信是通过

但是,我遇到了意外反应的问题:当我更改子组件中的属性时,它们也会立即在父组件中更新。

我的总体问题是:props 是父数据的副本,还是指针?

具体来说,我将应用程序中定义的数据发送给我的子组件:

<current-incident
  @updated-incident="updateAllincidentsFromIncidentForm"
  :currentIncident="currentIncident"
/>

currentIncident在应用程序中定义data()

data() {
   return {
      currentIncident: {
         id: null
      },
      allIncidents: {},
   }
},

从组件的角度来看,作为 a 接收的prop是一个 Object ( ),然后将其分配给在组件 ( )中props: ['currentIncident']定义的内部对象。data()mount()this.incident = this.currentIncident

this.incident然后在组件中进行修改,并最终用this.$emit().

currentIncident问题是当我在组件中修改时,父的内容会被即时修改incident还没有发生$emit()

这让我认为prop通过:currentIncident="currentIncident"双向绑定传递currentIncident,在我的理解中,这正是创建 props 和 emits 的原因(以打破这种双向绑定)

标签: vue.jsvue-reactivity

解决方案


我在文档中找到了答案:

请注意,JavaScript 中的对象和数组是通过引用传递的,因此如果 prop 是数组或对象,则在子组件内改变对象或数组本身影响父状态。

解决方案是将道具值(我使用lodash)深度克隆到一个新变量中(然后$emit如问题中所述)


推荐阅读