【问题标题】:count child components programmatically以编程方式计算子组件
【发布时间】:2021-11-20 12:24:12
【问题描述】:

在 Vue 应用程序中,正在开发的页面具有多个子组件。每个孩子向父母发出一个事件。下面是模板中几个组件的代码sn-p:

<warehouses-01 @component-loaded="() => this.componentsLoaded.push('warehouses-01')" />
<warehouses-03 @component-loaded="() => this.componentsLoaded.push('warehouses-03')" />
<warehouses-04 @component-loaded="() => this.componentsLoaded.push('warehouses-04')" />
<warehouses-07 @component-loaded="() => this.componentsLoaded.push('warehouses-07')" />

脚本标签中的相关代码-

export default {
    watch: {
        componentsLoaded() {
            if (this.componentsLoaded.length === 4) this.isLoaded = true;
        }
    },
    data() {
        return {
            componentsLoaded: [],
            isLoaded: false
        }
    }
}

isLoaded 属性变为真时,其他代码(上面未显示)将采取行动。问题是当添加新的子组件时,需要手动更新观察器中的硬编码值。我多次忘记了这个手动更新步骤,然后想知道为什么页面没有按预期运行。为了消除这一步 - 有没有办法以编程方式计算子组件的数量,或者更好的是,计算发出“组件加载”事件的子组件的数量?

【问题讨论】:

  • 你可以试试这个:this.componentsLoaded.length === this.$children.filter( i =&gt; i.$listeners['component-loaded'] ).length
  • @Fab 是的!那行得通。非常感谢。
  • 完美!我将其添加为答案

标签: vue.js


【解决方案1】:

这可能是一个解决方案:

watch: {
    componentsLoaded() {
        let componentCounter = this.$children.filter( i => i.$listeners['component-loaded'] ).length;
        if (this.componentsLoaded.length === componentCounter) this.isLoaded = true;
    }
},

【讨论】:

  • 为了实现,我选择在挂载的生命周期钩子中创建componentCounterthis.componentCounter,这样它只执行一次,而不是每次触发观察者时。
猜你喜欢
  • 2015-08-30
  • 1970-01-01
  • 1970-01-01
  • 2011-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-14
  • 1970-01-01
相关资源
最近更新 更多