Разделить массив на блоки разного размера N - PullRequest
0 голосов
/ 28 мая 2020

Мне было интересно, возможно ли это в VueJS

У меня есть массив из N элементов, и я хочу разбить его на массивы разной длины, чтобы в конечном итоге вывести что-то вроде этого (обратите внимание на первую строку имеет два столбца, а второй - 3)

Array = [{"text": "hello"},{"text": "hello1"},{"text": "hello2"},{"text": "hello3"},{"text": "hello4"},{"text": "hello5"},{"text": "hello6"},{"text": "hello7"},{"text": "hello8"}]
<div class="row">
    <div class="col-1-of-2">
       hello
    </div>
    <div class="col-1-of-2">
        hello1
    </div>
</div>
<div class="row">
    <div class="col-1-of-3">
       hello2
    </div>
    <div class="col-1-of-3">
        hello3
    </div>
    <div class="col-1-of-3">
        hello4
    </div>
</div>

И повторите

Я бы подумал, что вам нужно разбить массив на части, но примеры, которые я видел, предполагают фиксированный Длина N

Ответы [ 2 ]

0 голосов
/ 28 мая 2020

Можно сделать примерно так:

new Vue({
  el: "#app",
  data() {
    return {
      items: [{"text": "hello"},{"text": "hello1"},{"text": "hello2"},{"text": "hello3"},{"text": "hello4"},{"text": "hello5"},{"text": "hello6"},{"text": "hello7"},{"text": "hello8"}],
      size: 2
    }
  },
  computed: {
    rows() {
      let _newContent = [];

      while(this.items.length > 0) {
        _newContent.push(this.items.splice(0, this.size));
      }

      return _newContent;
    }
  },
})
0 голосов
/ 28 мая 2020

Самый распространенный способ справиться с этим - использовать вычисляемый.

Возьмите массив и вложите его по мере необходимости (не уверен, какие у вас правила для наличия 2 и 3)

а затем используйте вложенные циклы в шаблоне для отображения данных

new Vue({
  el: "#app",
  data() {
    return {
      split: "2,3",
      items: [{"text": "hello"},{"text": "hello1"},{"text": "hello2"},{"text": "hello3"},{"text": "hello4"},{"text": "hello5"},{"text": "hello6"},{"text": "hello7"},{"text": "hello8"},{"text": "hello9"}]
    }
  },
  computed: {
    rows() {
      const { split, items } = this;
			let ret = [];
      let si = 0;
      let ci = 0;
      let splitArr = split.split(',');
      this.items.forEach(item => {
        if(!ret[si]){ret.push([])}
        ret[si][ci] = item
        ci = (ci + 1)
        if (ci >= splitArr[si % splitArr.length]) {
        	ci = 0;
          si++;
        }
        
      })
      return ret
    }
  },
})
.row{
  display: block;
}
.col{
  box-sizing: border-box;
  padding: 10px;
  margin: 2px;
  border: 1px solid;
  display: inline-block;
}
.col-1-of-1{
  width: calc(100% - 4px);
}
.col-1-of-2{
  width: calc(50% - 4px);
}
.col-1-of-3{
  width: calc(33.3% - 4px);
}
.col-1-of-4{
  width: calc(25% - 4px);
}
.col-1-of-5{
  width: calc(20% - 4px);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
  <div>
    SPLIT: <input v-model="split">
  </div>
  <div class="row" v-for="row in rows">
    <div :class="`col col-1-of-${row.length}`" v-for="col in row">
      {{col.text}}
    </div>
  </div>
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...