计算子组件的出现次数 [英] Count the occurrences of a child component
本文介绍了计算子组件的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的单个文件组件:
<div><模板 v-if="offers.length > 3"><a href="#">在此处查看所有优惠</a></模板><模板 v-else-if="offers.length > 1"><offer v-for="offer in offer" :data="offer"></offer></模板><模板 v-else-if="offers.length == 1"><offer :title="The offer" :data="offers[0]"></offer></模板>
</模板>
根据offer
的数量,我选择要渲染的数量.
问题:如何有效地获取/计算
组件的数量?我也需要这个数字是反应性的.
解决方案
没有干净的方法.
您可以计算当前实例的特定类型的子项.但是您必须在 update
挂钩(以及 mounted
)上调用重新计数"逻辑.
示例:
Vue.component('offer', {name: '报价',模板:'<span>提供</span>'})新的 Vue({el: '#app',数据: {提供:[1, 2],报价数:0},方法: {更新优惠计数(){this.offerCount = this.$children.filter(child => child.constructor.options.name === 'Offer').length;}},更新() {this.updateOfferCount()},安装(){this.updateOfferCount()}})
<script src="https://unpkg.com/vue"></script><div id="应用程序"><div><模板 v-if="offers.length > 3"><a href="#">在此处查看所有优惠</a></模板><模板 v-else-if="offers.length > 1"><offer v-for="offer in offer" :data="offer"></offer></模板><模板 v-else-if="offers.length == 1"><offer :data="offers[0]"></offer></模板>
<br><button @click="offers.push(123)">添加优惠</button>offerCount: {{ offerCount }}
I have a single file component like this:
<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>
Based on the number of offers
, I choose how many to render.
Question: How do I efficiently get/count the number of <offer>
components? I also need that number to be reactive.
解决方案
There's no clean way how.
You could count the children of the current instance that are of a specific type. But you would have to call the "recount" logic on update
hook (as well as mounted
).
Example:
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>
这篇关于计算子组件的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!