vue.js - 如何将对象数组拆分为多个 div 列

Sye*_*yed 5 javascript arrays vue.js vuejs2

这是我的 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>
Run Code Online (Sandbox Code Playgroud)

目标是:

<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>
Run Code Online (Sandbox Code Playgroud)

在像 Flask 和 Jinja 这样的基于 Python 的微框架中,可以这样做:

{% for article_row in articles | batch(3, '&nbsp;') %}
  <div class="row">
    {% for article in article_row %}
    <div class="span4">{{ article }}</div>
    {% endfor %}
  </div>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

那么,有没有办法在 vue.js 中做到像上面那样?

Bil*_*ell 10

我会使用计算属性将它们组合起来。如果你lodash有空,你可以这样做:

computed: {
  chunked () {
    return _.chunk(this.articles, 3)
  },
},
Run Code Online (Sandbox Code Playgroud)

如果你没有 lodash,你可以在所有地方找到分块的逻辑,这将起作用。

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
}
Run Code Online (Sandbox Code Playgroud)

然后,你可以这样做:

<div class="row" v-for="chunk in chunked">
  <div class="col-4" v-for="article in chunk">
    {{ article.name }}
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)


dfs*_*fsq 9

我会使用辅助组数组来呈现行中的文章组:

<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>
Run Code Online (Sandbox Code Playgroud)

演示: https : //codesandbox.io/s/rj60o8l5p