Reputation: 2435
I'm starting to face this issue more and more often and am wondering if there is a simple solution to this. Kinda stuck trying to loop through a set of data into a row/child kind of structure.
Here's what I'm trying to achieve.
<div class="row">
<div>Data 1</div>
<div>Data 2</div>
<div class="row">
<div>Data 3</div>
...
What I ended doing most of the time is to just now house my data loops into a row, etc. But it prevented me from displaying my data in a more customised way... Is there a better way?
<div v-for="item in items">
<div class="row">
<div>{{ item.message }}</div>
</div>
</div>
Like after 3 item.messages, a new row will spawn, etc?
Upvotes: 3
Views: 47
Reputation: 82489
Typically how I would handle this is use a computed value to group the data in the manner I wanted, and then iterate over the grouped data.
console.clear()
new Vue({
el: "#app",
data:{
todos: [
{id: 1, text: "learn Vue"},
{id: 2, text: "learn Vuex"},
{id: 3, text: "learn Vue Router"},
{id: 4, text: "learn javascript"},
{id: 5, text: "wash dishes"},
{id: 6, text: "go to gym"},
{id: 7, text: "go out with Sally"},
],
todosPerRow: 3
},
computed:{
grouped(){
return this.todos.reduce((acc, val, ndx) => {
let key = Math.floor(ndx / this.todosPerRow)
if (acc[key]) acc[key].push(val)
else acc[key] = [val]
return acc
}, {})
}
}
})
.row {
border: 1px solid
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.7/vue.js"></script>
<div id="app">
<template v-for="group in grouped">
<div class="row">
<div v-for="todo in group">{{todo.text}}</div>
</div>
</template>
</div>
Here I just wrote a quick and dirty grouping function. Libraries like lodash also implement a groupBy
method you could use instead.
Upvotes: 2