Home > Back-end >  How to dynamically bind a color to each object in a collection?
How to dynamically bind a color to each object in a collection?

Time:12-28

I'm trying to change the background color like 1st row would be black while 2nd row would be white and it would continue in the same sequence

<template>
  <div
    v-for="(activity, index) in logActivities"
    :key="index"
    
  >
    <div >{{ activity.activity }}</div>
    <div >
      {{ toGetRelativeTime(activity.createdAt) }}
    </div>
  </div>
</template>

CodePudding user response:

One way with checking if index is even or odd:

new Vue({
  el: "#demo",
  data() {
    return {
      logActivities: [{activity: 'aa', createdAt: 1}, {activity: 'bb', createdAt: 2}, {activity: 'cc', createdAt: 3}, {activity: 'dd', createdAt: 4}, {activity: 'ee', createdAt: 5}]
    }
  }
})
.bg-black {
  background: black;
  color: white;
}
.bg-white {
  background: white;
  color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <div
    v-for="(activity, index) in logActivities"
    :key="index"
    :
    >
    <div>{{ activity.activity }}</div>
    <div>
    {{ activity.createdAt }}
    </div>
  </div>
</div>

CodePudding user response:

I don't have enough reputation yet to comment on kissu's answer, but I want to add that when using Tailwind (supposing you're using it) you can also do something like this:

<template>
  <div
    v-for="(activity, index) in logActivities"
    :key="index"
    
  >
    <div >{{ activity.activity }}</div>
    <div >
      {{ toGetRelativeTime(activity.createdAt) }}
    </div>
  </div>
</template>

This will add black background for odd rows, and white background for even rows.

You can check this out on Tailwind documentation enter image description here

  • Related