值是对象的属性可能特别棘手。如果您更改该对象中的属性,则状态不会更改。因此,子组件不会得到更新。
检查这个例子:
// ParentComponent.vue
<template>
<div>
<child-component :some-prop="anObject" />
<button type="button" @click="setObjectAttribute">Click me</button>
</div>
</template>
<script>
export default {
data() {
return {
anObject: {},
};
},
methods: {
setObjectAttribute() {
this.anObject.attribute = 'someValue';
},
},
};
</script>
// ChildComponent.vue
<template>
<div>
<strong>Attribute value is:</strong>
{{ someProp.attribute ? someProp.attribute : '(empty)' }}
</div>
</template>
<script>
export default {
props: [
'someProp',
],
};
</script>
当用户点击“点击我”按钮时,本地对象被更新。然而,由于对象本身是相同的——只是它的属性发生了变化——没有调度状态变化。
要解决这个问题,setObjectAttribute 可以这样更改:
setObjectAttribute() {
// using ES6's spread operator
this.anObject = { ...this.anObject, attribute: 'someValue' };
// -- OR --
// using Object.assign
this.anObject = Object.assign({}, this.anObject, { attribute: 'someValue' });
}
通过这样做,anObject 数据属性正在接收一个新的对象引用。然后,状态发生变化,子组件将收到该事件。