首页 > 解决方案 > 计算子组件的出现次数

问题描述

我有一个这样的文件组件:

<template>
    <div>
        <template v-if="offers.length > 3">
            <a href="#">View all offers here</a>
        </template>

        <template v-else-if="offers.length > 1">
            <offer v-for="offer in offers" :data="offer"></offer>
        </template>

        <template v-else-if="offers.length == 1">
            <offer :title="The offer" :data="offers[0]"></offer>
        </template>
    </div>
</template>

根据 的数量offers,我选择要渲染的数量。

问题:如何有效地获取/计算<offer>组件的数量?我还需要这个数字是被动的。

标签: javascriptvuejs2vue-component

解决方案


没有干净的方法。

您可以计算当前实例的特定类型的子代。但是您必须在update挂钩(以及mounted)上调用“重新计数”逻辑。

例子:

Vue.component('offer', {
  name: 'Offer',
  template: '<span> offer </span>'
})
new Vue({
  el: '#app',
  data: {
    offers: [1, 2],
    offerCount: 0
  },
  methods: {
    updateOfferCount() {
      this.offerCount = this.$children.filter(child => child.constructor.options.name === 'Offer').length;
    }
  },
  updated() {
    this.updateOfferCount()
  },
  mounted() {
    this.updateOfferCount()
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <div>
    <template v-if="offers.length > 3">
        <a href="#">View all offers here</a>
    </template>

    <template v-else-if="offers.length > 1">
        <offer v-for="offer in offers" :data="offer"></offer>
    </template>

    <template v-else-if="offers.length == 1">
        <offer :data="offers[0]"></offer>
     </template>
  </div>
  <br>
  <button @click="offers.push(123)">Add Offer</button> offerCount: {{ offerCount }}
</div>


推荐阅读