K
K
KRHD2020-03-03 15:20:33
Vue.js
KRHD, 2020-03-03 15:20:33

How to reset the index at a certain v-for iteration?

There is a v-for and during a certain iteration need index (which is the iteration number)
Return null, how to do it?

The problem is that it should be reset to zero when the iteration in the item.depth variable is null

Answer the question

In order to leave comments, you need to log in

3 answer(s)
0
0xD34F, 2020-03-03
@KRHD

Can be done...

  • ...a computed property, where the desired value will be attached to the array elements:
    computed: {
      itemsWithBullshitCounter() {
        let counter = -1; /* или 0, если хотите, чтобы нулевой элемент массива получил ненулевой индекс
                             в том случае, если для него не выполняется условие обнуления */
        return this.items.map((n, i) => ({
          ...n,
          counter: counter = (здесь проверяете, надо ли обнулить счётчик
            ? 0
            : counter + 1
          ),
        }));
      },
    },

    <div v-for="n in itemsWithBullshitCounter">
      вместо индекса используете значение добавленного свойства: {{ n.counter }}
    </div>

    https://jsfiddle.net/hk93q6gf/
  • ...a computed property where the original array will be split into multiple chunks:
    computed: {
      chunkedItems() {
        return this.items.reduce((acc, n, i) => {
          if (!i || на текущем элементе надо сбросить индексацию) {
            acc.push([]);
          }
    
          acc[acc.length - 1].push(n);
    
          return acc;
        }, []);
      },
    },

    <template v-for="chunk in chunkedItems">
      у каждого куска индексация независимая:
      <div v-for="(n, i) in chunk">{{ i }}</div>
    </template>

    https://jsfiddle.net/hk93q6gf/1/
  • ...a method that will calculate the desired index (bad - calculations are performed on each render):
    methods: {
      createStrangeIndex(arr, baseIndex) {
        let index = 0;
    
        while (baseIndex > 0 && на элементе arr[baseIndex--] сбрасывать индексацию не надо) {
          index++;
        }
    
        return index;
      },
    },

    <div v-for="(n, i) in items">{{ createStrangeIndex(items, i) }}</div>

    https://jsfiddle.net/hk93q6gf/2/

N
nvdfxx, 2020-03-03
@nvdfxx

<div for="(item, index) in items">
ID: {{index % x}} // x - определенная итерация
</div>

p.s. Chances are if you need a solution via an index, 99% that you are doing something wrong

D
Denis Ineshin, 2020-03-03
@IonDen

Maybe you should just restart the loop in this case? The effect is the same.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question