如何使用Vue 2.0的对象React性?

yb3bgrhw  于 7个月前  发布在  Vue.js
关注(0)|答案(2)|浏览(64)

我有一个带有特定数据的父组件:

data: function() {
        return {
           initialItem: { name: "item", size: 10, description: "some text" }
           currentItem: null
        };
    },
mounted() {
  this.currentItem = _cloneDeep(item);
}

字符串
在父模板中,我传递currentItem作为prop:

<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;,但到目前为止似乎都没有工作。
有人能告诉我这里可能遗漏了什么吗?这样,当有人单击“丢弃”按钮时,该项目就可以返回到其初始值。

s6fujrry

s6fujrry1#

发生这种情况的一个可能原因是,当您单击放弃更改按钮时,currentItem的值被设置回其初始值,但该更改不会导致子组件呈现已更改的属性。
子组件接收属性作为prop,它不会创建React依赖项。因此,父组件中对prop的更改不会自动传播到子组件
你可以做的是在你的子组件中添加一个观察者。一旦prop值改变了,你也可以在子组件中更新它。
所以在你的子文件中,添加这样的东西:

watch () {
  item () {
    this.itemDetail = this.item // deep copy if needed
  }

字符串

3j86kqsm

3j86kqsm2#

关键的改变技术可以做到这一点,因为这将有助于重新呈现您的子组件。

1.向子组件添加键:
第一个月
1.将componentKey属性添加到父组件数据:

data: function() {
        return {
           initialItem: { name: "item", size: 10, description: "some text" }
           currentItem: null,
           componentKey: 1,
        };
    },

字符串
1.物料更改时更新密钥:

updateItem(item) {
   this.currentItem = item
   this.componentKey ++
}

discardChanges() {
  this.currentItem = this.initialItem
  this.componentKey ++
}

相关问题