javascript - 计算子组件的出现次数
问题描述
我有一个这样的文件组件:
<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>
组件的数量?我还需要这个数字是被动的。
解决方案
没有干净的方法。
您可以计算当前实例的特定类型的子代。但是您必须在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>
推荐阅读
- sql - 我在掩盖表中列的值时遇到问题
- r - Lat-long 使用来自 ggmap 的地理编码
- android - 如何在 ActiveAndroid orm 中保存树 json?
- javascript - 将新的 NuxtJS 应用与现有的 Express API 一起使用
- sql - 删除或保留列中的数据 - SQL
- javascript - 使用包不渲染的 D3 v5 气泡图
- reactjs - React 秒表计时器未按预期工作
- mysql - 如何在 Windows8 中启动和停止 MYSQL DB
- python - 如何在视频 n 秒后运行特定代码
- selenium - 如何验证硒中两个单词之间有多个空格的文本?