这是我的vue布局:
<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>目标是:
<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>在基于Python的(如Flask和Jinja )中,可以这样做:
{% for article_row in articles | batch(3, ' ') %}
<div class="row">
{% for article in article_row %}
<div class="span4">{{ article }}</div>
{% endfor %}
</div>
{% endfor %}那么,在vue.js中有这样的方法吗?
发布于 2018-04-26 08:41:16
我将使用helper数组在行中呈现项目组:
<template lang="pug">
.container
.row(v-for="(group, i) in articleGroups")
.col-4(v-for="article in articles.slice(i * itemsPerRow, (i + 1) * itemsPerRow)")
| {{ article.name }}
</template>
<script>
export default {
name: 'Articles',
data() {
return {
itemsPerRow: 3,
articles: [
{ name: 'Article 1' },
{ name: 'Article 2' },
{ name: 'Article 3' },
{ name: 'Article 4' },
{ name: 'Article 5' },
{ name: 'Article 6' },
]
}
},
computed: {
articleGroups () {
return Array.from(Array(Math.ceil(this.articles.length / this.itemsPerRow)).keys())
}
},
}
</script>发布于 2018-04-26 08:49:02
我会用一个计算的属性把它们分块。如果您有可用的lodash,您可以:
computed: {
chunked () {
return _.chunk(this.articles, 3)
},
},如果你周围没有房客的话,你可以找到到处乱跑的逻辑。
function chunk (arr, len) {
const chunks = []
const i = 0
const n = arr.length
while (i < n) {
chunks.push(arr.slice(i, i += len))
}
return chunks
}然后,你可以:
<div class="row" v-for="chunk in chunked">
<div class="col-4" v-for="article in chunk">
{{ article.name }}
</div>
</div>发布于 2018-04-26 08:21:55
v-for="(article,i) in articles"与v-if="i>=0 && i<3"的结合
https://stackoverflow.com/questions/50038129
复制相似问题