vue.js - Как разбить массив объектов на несколько столбцов div - PullRequest
0 голосов
/ 26 апреля 2018

Вот мой макет 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 Micro Framework, таком как Flask и Jinja, это можно сделать следующим образом:

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

Итак, есть ли способ сделать, как описано выше, в vue.js?

Ответы [ 4 ]

0 голосов
/ 06 октября 2018

Используя .reduce, вы можете разбить ваш массив на группы по X.

<template>
    <div class="container">
        <template v-for="group in groupedArticles">
            <div class="row">
                <span v-for="article in group">
                    {{ article.title }}
                </span>
            </div>
        </template>
    </div>
</template>

<script>
    export default {
        data: function() {
            return {
                articles: [
                    { id: 1, title: 'Hello People' },
                    { id: 2, title: 'What Time is it?' },
                    { id: 3, title: 'Dogs & Cats' }
                ],
                itemsPerRow: 2
            }
        },
        computed: {
            groupedArticles: function() {
                return this.articles.reduce((accumulator, article, index) => {
                    if (index % this.itemsPerRow == 0) {
                        accumulator.push([article]);
                    } else {
                        accumulator[accumulator.length - 1].push(article);
                    } 

                    return accumulator;
                }, []);
            }
        },
    }
</script>
0 голосов
/ 26 апреля 2018

Я бы использовал массив групп помощников для визуализации групп статей в строках:

<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>

Демонстрация: https://codesandbox.io/s/rj60o8l5p

0 голосов
/ 26 апреля 2018

Я бы использовал вычисленное свойство, чтобы разделить их на части.Если у вас есть 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>
0 голосов
/ 26 апреля 2018

комбинация v-for="(article,i) in articles" и v-if="i>=0 && i<3"

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...