【发布时间】:2021-05-21 15:16:31
【问题描述】:
我有一个结构如下的 Vue 3 应用程序:
+---------------------+
| Component |
| +-----------------+ |
| | Child Component | |
| +-----------------+ |
+---------------------+
组件定义如下:
my-component.vue
<template>
<button @click="addItem" />
<child-component :items="items" />
</template>
<script>
import Child from './my-child-component.vue';
export default {
components: { 'child-component' : Child },
data() {
items: {} // NOTE: This is an object, not an array
},
methods: {
addItem() {
var count = Math.floor((Math.random() * 100) + 1);
var name = 'item' + count;
var children = [];
for (var i=0; i<count; i++) {
children.push(i+1);
}
this.items[name] = children;
}
}
}
</script>
my-child-component.vue
<template>
<div>Details of the Items</div>
</template>
<script>
export default {
props: {
items: {
type: Object,
default: {}
}
}
watch: {
items() {
console.log('the items have changed');
}
}
}
</script>
此代码动态地将属性添加到items 对象。不幸的是,child-component 没有看到 items 对象的变化。在 Vue 2 中,有一个 $vm.set 方法来解决这种情况。但是,我不确定如何在 Vue 3 中解决这个问题。
如何以子组件知道更改的方式动态更新对象?
谢谢!
【问题讨论】: