Vue.js Vue 3-向下树广播属性更改

Vue.js Vue 3-向下树广播属性更改,vue.js,vuejs3,Vue.js,Vuejs3,我有一个Vue 3应用程序的结构如下: +---------------------+ | Component | | +-----------------+ | | | Child Component | | | +-----------------+ | +---------------------+ 组件的定义如下: +---------------------+ | Component | | +-----------------+ | | |

我有一个Vue 3应用程序的结构如下:

+---------------------+
| Component           |
| +-----------------+ |
| | Child Component | |
| +-----------------+ |
+---------------------+
组件的定义如下:

+---------------------+
| Component           |
| +-----------------+ |
| | Child 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>
<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>

从“/my Child component.vue”导入子组件;
导出默认值{
组件:{'child component':child},
数据(){
items:{}//注意:这是一个对象,不是数组
},
方法:{
附加项(){
var count=Math.floor((Math.random()*100)+1);
变量名称='项目'+计数;
var children=[];

对于(var i=0;i,由于监视的属性是一个对象,您应该添加
deep:true
选项:

    watch: {
      items: {
         handler(){
          console.log('the items have changed');
           },
        deep:true
       
      }
    }

当您使用Vue3的
setup()
函数时,属性将作为第一个参数传递给它,保持它们的反应性。下面是一个工作示例,它会在每次属性更改时触发观察者:

const appConfig={
数据(){
返回{
项目:{}
}
}
};
const app=Vue.createApp(appConfig);
app.component('ChildComponent'{
道具:{
项目:{
类型:对象,
默认值:{}
}
},
模板:“项:{{items}}”,
设置(道具){
Vue.watch(props.items,()=>{
控制台日志(“项目变更”);
});
返回{
道具:道具
}
}
});
app.mount(“#app”);

添加