How do I display the data in the table that create a new row every 5th <td>
?
example
data: [1,2,3,4,5,6];
component:
<tr v-for="item in data">
<td>{{item}}</td>
<tr>
expected:
| 1 | 2 | 3 | 4 | 5 |
| 6 |
How do I display the data in the table that create a new row every 5th <td>
?
example
data: [1,2,3,4,5,6];
component:
<tr v-for="item in data">
<td>{{item}}</td>
<tr>
expected:
| 1 | 2 | 3 | 4 | 5 |
| 6 |
Here's a easy to understand solution using reduce
:
new Vue({
el: '#root',
data: {
origin: [1, 2, 3, 4, 5, 6, 7]
},
computed: {
chunkedOrigin: function() {
return this.origin.reduce((result, item, index) => {
const chunkIndex = Math.floor(index/5)
if(!result[chunkIndex]) {
result[chunkIndex] = [] // start a new chunk
}
result[chunkIndex].push(item)
return result;
}, []);
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<table id="root" style="border: 1px solid black">
<tr v-for="row in chunkedOrigin">
<td v-for="column in row" style="border: 1px solid black">{{column}}</td>
</tr>
</table>
You could create a computed
property to group the array into chunks of 5 items. Then loop through 2D array and create rows and columns
new Vue({
el: '#example',
data: {
array: [1, 2, 3, 4, 5, 6]
},
computed: {
grouped: function() {
const n = 5; // chunk size
const length = Math.ceil(this.array.length / n);
return Array.from({ length }, (_, i) => this.array.slice(i * n, (i + 1) * n))
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<table id="example">
<tr v-for="row in grouped">
<td v-for="column in row">{{column}}</td>
</tr>
</table>
You could use splice
method in while loop based on you chunk size you can convert into the 2-d array.
Code Snippet
new Vue({
el: '#example',
data: {
array: [1, 2, 3, 4, 5, 6]
},
computed: {
lists: function() {
const n = 5, // chunk size
gdata = [],
data = this.array;
while (data.length) {
gdata.push(data.splice(0, n));
}
return gdata;
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<table id="example">
<tr v-for="row in lists">
<td v-for="column in row">{{column}}</td>
</tr>
</table>
In vue JS loop there is a second parameter that represent the index.
<tr v-for="(item,index) in data">
<td v-if="(index % 5 == 0)">{{item}}</td>
<tr>
So you could use this index to apply a condition on it. For example using the modulo to verify if the index is a multiple of 5