Search code examples
javascriptvue.jsvuejs3

Vue 3 v-for local variable


I am using vue-3 have the following problem:

My app holds a list of chapters, and each one its sections:

[
  {
    "title":"Chapter 1",
    "sections":[
      {
        "title":"Section 1",
        "numPages":14
      },
      {
        "title":"Section 2",
        "numPages":8
      },
      {
        "title":"Section 3",
        "numPages":12
      }
    ]
  },
  {
    "title":"Chapter 2",
    "sections":[
      {
        "title":"Section 1",
        "numPages":5
      },
      {
        "title":"Section 2",
        "numPages":7
      }
    ]
  }
]

I need to print it in the following format:

Chapter 1
   Section 1     1 - 14
   Section 2     15 - 22
   Section 3     23 - 34
Chapter 2
   Section 1     35 - 40
   Section 2     41 - 47

In other words, for each chapter I need to print the range of pages, using this formula:

// init
lastToPage = 1

// each section
fromPage = lastToPage + 1
toPage = lastToPage numPages
lastToPage = toPage

The question:
Is there a way to have an accumulator variable inside v-for loop? (in order to keep lastToPage value)
Any other better solution?


Solution

  • Following suggestion of @Jaromanda, I came with this solution.

    In the template I replaced:

    <template v-for="chapter in chapters">
    

    with:

    <template v-for="chapter in extendedChapters">
    

    And added a computed variable extendedChapters:

    const extendedChapters = computed(() => {
      let extendedChapters = chapters.value
      extendedChapters.reduce(
          (acc, chapter) => chapter['events'].reduce((acc, event) => (event.firstPage = acc, acc + event['numPages']), acc), 1
      );
      return extendedChapters
    })