Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment counter in nested v-for

Tags:

I have a nested data structure like so:

allItems: [
    ['a', 'b', 'c'],
    ['d', 'e', 'f'],
    ['g', 'h', 'i'],
]

that I need to represent exactly like this:

Category 1
..........(a) Item 1
..........(b) Item 2
..........(c) Item 3
Category 2
..........(d) Item 4
..........(e) Item 5
..........(f) Item 6
Category 3
..........(g) Item 7
..........(h) Item 8
..........(i) Item 9

But I am not able to keep a counter in between v-for... Note that I have no control over the data and user will be offered to sort data however he wants making it impossible for me to add a counter within the data.

Here is a fiddle

like image 702
Jona Rodrigues Avatar asked Apr 25 '19 09:04

Jona Rodrigues


1 Answers

You can do something like:

<template>
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <div v-for="(row,i) in allItems" :key="row">
    Category {{i+1}}
    {{ updateCnt(row, i) }}

    <div v-for="(col,j) in row" :key="col">
...................({{col}}) Item {{ cnt + j + 1}}
    </div>

  </div>
</div>

</template>

<script>

new Vue({
  el: '#app',
  data: {
    allItems: [
      ['a', 'b', 'c'],
      ['d', 'e', 'f'],
      ['g', 'h', 'i'],
    ], 
    cnt: 0
  },
  methods: {
    updateCnt(row, i) {
      this.cnt = i * row.length;
    }
  }
})

</script>
like image 110
Sajib Khan Avatar answered Nov 15 '22 06:11

Sajib Khan