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

Questions:

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-card
   class="col-12"
   v-for="(course, index) in APIData.allClasses"
   :key="course.subject"
   v-bind:style="{color: APIData.classBackGround[index]}"
>
   {{ course.subject }}
</v-card>

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?

Answers:

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.