Vuejs V-for Add Bootstrap Row Every 5 Items
I have an array of items like 'Item 1', 'Item 2' up to 'Item 25'. I want the HTML after rendering look like this:
Item 1
Solution 1:
You can try this:
<divclass="row"v-for="i in Math.ceil(items.length / 5)"><spanv-for="item in items.slice((i - 1) * 5, i * 5)">
{{item}}
</span></div>
See a working example:
newVue({
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;
}
<scriptsrc="https://vuejs.org/js/vue.min.js"></script><divid="demo"><divclass="row"v-for="i in Math.ceil(items.length / 5)"><spanv-for="item in items.slice((i - 1) * 5, i * 5)">
{{item}}
</span></div></div>
Solution 2:
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() {
returnMath.ceil(this.items.length / this.itemsPerRow);
}
},
Solution 3:
Or you can do the same using lodash _.chunk()
, which personally I find more readable.
Template:
<divclass="columns"v-for="chunk in productChunks"><divclass="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
'
Solution 4:
A little improved answer, With npm install --save lodash
.
<template>
<divclass="content"><divclass="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';
exportdefault {
name: "ProductList",
components: {
"product-thumbnail": ProductThumbnail
},
data() {
return {
sps: [],
itemsPerRow: 4
}
},
asyncmounted() {
let resp = await;
//call apithis.sps = results;
},
computed: {
productChunks() {
return lodash.chunk(Object.values(this.sps), this.itemsPerRow);
}
}
}
Solution 5:
If you're simply creating placeholders/slots for content that you'll probably render later using position: relative
, you can create them like this:
<template><divclass="col q-gutter-y-xs"><divclass="row q-gutter-x-xs"v-for="row in rows":key="row"><divclass="col slot text-white"v-for="col in columns":key="col"></div></div></div></template><script>exportdefault {
data() {
return {
rows: 7,
columns: 7
}
}
}
</script><style>.slot {
background: #444;
border-radius: 8px;
border: 1px#2e2d28 solid;
}
</style>
Post a Comment for "Vuejs V-for Add Bootstrap Row Every 5 Items"