vuejs v-for add bootstrap row every 5 items
A little improved answer, With npm install --save lodash
.
<template>
<div class="content">
<div class="row" v-for="chunk in productChunks">
<product-thumbnail :product="sp" v-for="sp in chunk" class="col-4"></product-thumbnail>
</div>
</div>
</template>
import lodash from 'lodash';
export default {
name: "ProductList",
components: {
"product-thumbnail": ProductThumbnail
},
data() {
return {
sps: [],
itemsPerRow: 4
}
},
async mounted() {
let resp = await;
//call api
this.sps = results;
},
computed: {
productChunks() {
return lodash.chunk(Object.values(this.sps), this.itemsPerRow);
}
}
}
In addition to the example above which I think is fine, I would define the calculations as computed properties and methods for more readable code. See the JSFiddle:
computed:{
rowCount() {
return Math.ceil(this.items.length / this.itemsPerRow);
}
},
Or you can do the same using lodash _.chunk()
, which personally I find more readable.
Template:
<div class="columns" v-for="chunk in productChunks">
<div class="column is-one-quarter" v-for="product in chunk">
// stuff
</div>
</div>
Then
computed: {
productChunks(){
return _.chunk(Object.values(this.products), 4);
}
},
Personally I import lodash globally as I use it so often, in main.js:
import _ from 'lodash'
Remember to 'npm install --save lodash
'
You can try this:
<div class="row" v-for="i in Math.ceil(items.length / 5)">
<span v-for="item in items.slice((i - 1) * 5, i * 5)">
{{item}}
</span>
</div>
See a working example:
new Vue({
el: '#demo',
data: {
items: [
'item 1',
'item 2',
'item 3',
'item 4',
'item 5',
'item 6',
'item 7',
'item 8',
'item 9',
'item 10',
'item 11',
'item 12',
'item 13',
'item 14',
'item 15',
'item 16',
'item 17',
'item 18',
'item 19',
'item 20',
'item 21',
'item 22',
'item 23',
'item 24',
'item 25'
]
}
})
.row {
border: solid 1px #404040;
padding: 10px;
}
<script src="https://vuejs.org/js/vue.min.js"></script>
<div id="demo">
<div class="row" v-for="i in Math.ceil(items.length / 5)">
<span v-for="item in items.slice((i - 1) * 5, i * 5)">
{{item}}
</span>
</div>
</div>