Kon*_*nov 4 javascript loops vue.js vue-component
我提供了通过循环呈现的卡片列表。每 3rd col (bootstrap) 元素我添加行 div。现在我需要为每 6 个元素添加另一个 col 元素(横幅块)。为了渲染这样的东西:
我该如何实现?
我现在的代码
<div class="row" v-for="i in Math.ceil(offers.length / 3)">
<div class="col-xl-4 col-lg-4 col-md-6 col-sm-12 col-12" v-for="offer in offers.slice((i-1)*3, i*3)">
<h2>{{offer.name}}</h2>
<h2>{{offer.desc}}</h2>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
小智 6
for循环:
<div class="mycol" v-for="(offer,ind) in offers">
<template v-if="ind % 5 == 0">
<h2>banner</banner>
</template>
<template v-else>
<h2>{{offer.name}}</h2>
<h2>{{offer.desc}}</h2>
</template>
</div>
Run Code Online (Sandbox Code Playgroud)
对于每三个列的新行,您可以使用 css
.mycol:nth-child(3n+1){
clear:left;
}
Run Code Online (Sandbox Code Playgroud)
我建议您少在视图中编程,多在视图模型中编程。创建一个computed将数据拆分为一系列优惠和横幅以及行的数据,然后以简单的方式使用计算结果。
const chunk = (arr, size) =>
arr
.reduce((acc, _, i) =>
(i % size) ?
acc :
[...acc, arr.slice(i, i + size)], []);
new Vue({
el: '#app',
data: {
offers: []
},
computed: {
rows() {
const withBanners = chunk(this.offers, 5).map((arr) => [...arr, {name: 'banner', type: 'Banner'}]).reduce((a, b) => a.concat(b), []);
return chunk(withBanners, 3);
}
},
mounted() {
setTimeout(() => {
this.offers = [{
name: 'offer'
},
{
name: 'offer'
},
{
name: 'offer'
},
{
name: 'offer'
},
{
name: 'offer'
},
{
name: 'offer'
},
{
name: 'offer'
},
{
name: 'offer'
},
{
name: 'offer'
},
{
name: 'offer'
},
{
name: 'offer'
}
];
}, 500);
}
});Run Code Online (Sandbox Code Playgroud)
#app {
display: grid;
}
.row {
display: grid;
grid-gap: 2rem;
grid-template-columns: repeat(3, auto);
justify-content: left;
}
.box {
width: 8rem;
height: 8rem;
}
.banner {
background-color: #f9c;
}
.offer {
background-color: #99f;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/vue@latest/dist/vue.js"></script>
<div id="app">
<div class="row" v-for="row in rows">
<div class="col-xl-4 col-lg-4 col-md-6 col-sm-12 col-12" v-for="item in row">
<div v-if="item.type === 'Banner'" class="banner box">
<h2>{{item.name}}</h2>
</div>
<div v-else class="offer box">
<h2>{{item.name}}</h2>
</div>
</div>
</div>
</div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4657 次 |
| 最近记录: |