Here is my vue layout:
<template lang="pug">
.row
.col-4(v-for="article in articles") // need to render 1-3 items here
| {{ article.name }}
.row
.col-4(v-for="article in articles") // need to render 4-6 items here
| {{ article.name }}
</template>
<script>
export default {
name: 'Articles',
data() {
return {
articles: [
{ name: 'Article 1' },
{ name: 'Article 2' },
{ name: 'Article 3' },
{ name: 'Article 4' },
{ name: 'Article 5' },
{ name: 'Article 6' },
]
}
},
}
</script>
The Goal is:
<div class="row">
<div class="col-4">article[0].name</div>
<div class="col-4">article[1].name</div>
<div class="col-4">article[2].name</div>
</div>
<div class="row">
<div class="col-4">article[3].name</div>
<div class="col-4">article[4].name</div>
<div class="col-4">article[5].name</div>
</div>
In Python based Micro Framework like Flask and Jinja, it's possible to do in this way:
{% for article_row in articles | batch(3, ' ') %}
<div class="row">
{% for article in article_row %}
<div class="span4">{{ article }}</div>
{% endfor %}
</div>
{% endfor %}
So, is there a way to do like above in vue.js?
I would use helper groups array to render groups of articles in rows:
Demo: https://codesandbox.io/s/rj60o8l5p
I'd use a computed property to chunk them up. If you have
lodash
available you can do:You can find the logic for chunking all over the place if you don't have lodash around this will work.
Then, you can do:
Using .reduce you can break your array into groups of X.
a combination of
v-for="(article,i) in articles"
andv-if="i>=0 && i<3"
The simpler way to use lodash.chunk() function in your code is:
Refer here for a detailed explanation of lodash.chunk() function: https://dustinpfister.github.io/2017/09/13/lodash-chunk/