Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeError: undefined Javascript Vue V-for

I have a function that returns an array of objects like this:

getMonthDaysGrid() {
    const totalLastMonthDays = this.getFirstDayOfMonth().dayNumber;
    const totalDays = this.month.numberOfDays + totalLastMonthDays;
    const monthList = Array.from({ length: totalDays });

    for (let i = totalLastMonthDays; i < totalDays; i++) {
      monthList[i] = {
        date: i - totalLastMonthDays + 1,
        month: this.month.name,
        year: this.month.year,
      };
    }

    return monthList;
  }

when I try to make a v-for div like this:

<div v-for="(day, idx) in cal.getMonthDaysGrid()" :key="idx">
        <p>
          {{ day.date }}
        </p>
      </div>

this throw me this error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

I can’t figure how to fix it… if it loops the array, how is that I can’t access the object properties?

>Solution :

It seems like Vue is trying to access the property before it is even seem so you would have to check if it exist first or just give the day array a default value

try changing your code to

<div v-for="(day, idx) in cal.getMonthDaysGrid()" :key="idx">
        <p>
          {{ day && day.date }}
        </p>
      </div>

or to

<div v-for="(day, idx) in cal.getMonthDaysGrid()" :key="idx">
        <p>
          {{ day?.date }}
        </p>
      </div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading