我有一个包含某些数据的父组件:
data: function() {
return {
initialItem: { name: "item", size: 10, description: "some text" }
currentItem: null
};
},
mounted() {
this.currentItem = _cloneDeep(item);
}
在父模板中,我将
currentItem
作为道具传递:
<child-component :item="currentItem" @set-item=updateItem />
<button @click="discardChanges">Discard changes</button>
updateItem(item) {
this.currentItem = item
}
discardChanges() {
this.currentItem = this.initialItem
}
我想要更新的 UI 项目位于子组件中,例如:
<input :value.sync="itemDetail.name" @click=emit('set-item') />
(...other similar inputs)
<script>
export const ChildComponent = {
props: {
item: {
type: Object,
required: true
}
},
data: function() {
return {
itemDetail: this.item
};
},
};
每当用户更改子组件中的属性时,都会向父组件发送一个事件,以进一步保存它。
问题出在丢弃处理程序中,因为即使变量相应地更改了其属性,UI 也没有反映它。
我也尝试过在
discardChanges
函数中使用 Vue.set(...)
、this.$forceUpdate()
、做 this.currentItem = null; this.currentItem = this.initialItem;
,但到目前为止,这些似乎都不起作用。
有人可以指出我在这里可能缺少的内容,以便当有人单击丢弃按钮时该项目返回到其初始值吗?
发生这种情况的一个可能原因是,当您单击“放弃更改”按钮时,currentItem 的值将设置回其初始值,但该更改不会导致子组件呈现更改的属性。
子组件接收属性作为 prop,并且它不会创建反应式依赖。因此,父组件中 prop 的更改不会自动传播到子组件
您可以做的是在您的子组件中添加一个观察者。一旦 prop 值发生变化,您也可以在子组件中更新它。
因此,在您的子文件中,添加如下内容:
watch () {
item () {
this.itemDetail = this.item // deep copy if needed
}