Home » vue » How to specify index of array in v-for in vuejs?

How to specify index of array in v-for in vuejs?

Posted by: admin November 26, 2021 Leave a comment


I have an array of color in my vuex state and in my component I want to specify each color for each element that comes from v-for.

// state
state: {
    APIData: {
      userInfo: {},
      allClasses: [
          subject: 'subject1',
          subject: 'subject2',
          subject: 'subject3',
      classBackGroud: ['red', 'blue', 'green',..],

here is what i have tried

// component
   v-for="(course, index) in APIData.allClasses"
   v-bind:style="{color: APIData.classBackGround[index]}"
   {{ course.subject }}

I want something like this, subject1 has color red, subject2 has color blue, subject3 has color green, ..etc.

With what i have tried i got this error

[Vue warn]: Error in render: "TypeError: Cannot read property '0' of undefined"

How can achieve it?


Your state object has classBackGroud but you are trying to render classBackGround. Seems like a spelling mistake. Otherwise, the code looks good to me. Try rectifying the property name.