What is the best way to link a unique color to every item in a collection dynamically?

I'm looking to alternate the background colors of the rows, with the first row being black and the second row being white, continuing in this sequence.

<template>
  <div
    v-for="(activity, index) in logActivities"
    :key="index"
    :class="[index % 2 === 0 ? 'row bg-black' : 'row bg-white']"
  >
    <div class="col-6 padding-10">{{ activity.activity }}</div>
    <div class="col-6 padding-10">
      {{ toGetRelativeTime(activity.createdAt) }}
    </div>
  </div>
</template>

Answer №1

Here is a method to determine whether an 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"
    :class="index % 2 === 0 ? 'bg-black' : 'bg-white'"
    >
    <div>{{ activity.activity }}</div>
    <div>
    {{ activity.createdAt }}
    </div>
  </div>
</div>

Answer №2

I currently lack the necessary reputation to leave a comment on kissu's response, but I would like to mention that in the context of using Tailwind CSS (assuming you are using it), there is another approach you can take:

<template>
  <div
    v-for="(activity, index) in logActivities"
    :key="index"
    class="row odd:bg-black even:bg-white"
  >
    <div class="col-6 padding-10">{{ activity.activity }}</div>
    <div class="col-6 padding-10">
      {{ toGetRelativeTime(activity.createdAt) }}
    </div>
  </div>
</template>

This will result in a black background for odd rows, and a white background for even rows.

You can refer to the relevant information on this feature in the Tailwind documentation here

Answer №3

Assuming you are utilizing Tailwind CSS, here is a way to achieve the desired result:

<template>
  <section class="grid grid-cols-3">
    <div
      v-for="activity in activities"
      :key="activity.id"
      :style="`background-color: ${activity.color}`"
      class="p-4 m-2 text-center"
    >
      {{ activity.name }}
    </div>
  </section>
</template>

<script>
export default {
  data() {
    return {
      activities: [
        { id: 1, color: 'green', name: 'Task A' },
        { id: 2, color: 'blue', name: 'Task B' },
        { id: 3, color: 'purple', name: 'Task C' },
      ],
    }
  },
}
</script>

Here is a preview of how it will appear:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The automatic sliding feature stops functioning once the controls have been clicked

When using the boxslider, the autosliding feature functions correctly initially. However, after manually clicking on the left and right arrow controls, the auto sliding stops working. See below for my code snippet: <ul id="slider-assocoates"> ...

Align the content to the center

Currently, I am in the process of creating a profile card view and utilizing Bootstrap to achieve this. I have set up two div elements - one with the class col-lg-3 and the other with col-lg-9. However, I am facing an issue where the content within col-lg ...

Unique phrase: "Personalized text emphasized by a patterned backdrop

I'm facing a challenge and struggling to find a way to highlight text using CSS or jQuery. My goal is to have an image on the left, another one on the right, and a repeated image in between. Since there are some long words involved, I need a dynamic s ...

Assistance needed with CSS selectors for implementing with selenium

<div id="footerSearchInputDefault" class="defaultText" style="visibility: hidden;">Search myTwonky</div> In relation to selenium, what do the following terms refer to in the above code snippet? attribute element value text label I often fin ...

Using Vue.js to list out every property key and the corresponding nested property values

Struggling to find the right title for my current dilemma. It's a bit complex to sum up in just one sentence. I'm faced with the challenge of looping through an imported object from a third-party package, but its structure is proving to be quite ...

"Troubleshooting a dropdown navigation bar problem in CSS

I am currently working on creating a CSS navbar dropdown, but I am encountering some issues. I am not very experienced with CSS, so any assistance would be greatly appreciated. The text within the "Products" box is not changing color like it should, and yo ...

Can you explain the process of utilizing CSS to create a smooth transition effect with

In the example application, I am utilizing the following plugin: I am perplexed by this line of code: style="width: 538px; transition: opacity 10000ms cubic-bezier(0.42, 0.65, 0.27, 0.99) 0s;. Can someone explain how the transition works? From what ...

Toggle sidebar: expand/collapse

Looking for some assistance with my website project. I currently have two arrows to open and close the sidebar, but I would like one button to handle both actions instead. Can someone help me edit my code snippet to achieve this? Keep in mind that I am new ...

Step-by-step guide on implementing a border-bottom for an active link

Is there a way to apply a border-bottom to btn_articles and btn_posts when one of them is clicked? I attempted to use the active class but it did not have the desired effect. Any suggestions or solutions would be greatly appreciated. let btn_articles = ...

Issue with Showing Hidden Section using Jquery - Try it Out on JSfiddle!

I'm struggling with a script that should reveal a hidden <div> when a checkbox is clicked. Despite my best efforts, I can't seem to get the section to display correctly. The snippet of code in question looks like this... If you'd like ...

I'm having trouble getting my text to center properly within a li container

I'm struggling to perfectly align the text in the middle of the li container. It seems to be centered horizontally, but vertically it's off. I've attempted adding a span to the text and adjusting the margin and padding, but so far I've ...

What is the best way to trigger card opening - through clicking or hovering?

Once the Set tag/status button on the left is clicked, I aim to display a card similar to this one on the right side. What would be the best approach to achieve this in React? Should I use regular CSS, Material UI, or React-bootstrap? https://i.stack.img ...

Unlocking the variables within a v-for loop post-mounted: A guide to accessing and updating them

I have a question regarding my code snippet below. The calculation of Ending Inventory involves adding the beginningInventory, newInventory, and totalSold values. How can I access the value property of endingInventory in order to update it? Any assistance ...

A guide to increasing a loop counter in Vue

Having trouble looping through a specific group of objects in a multi-object array? Take a look at the code below: <template> <div> <h1>My Test App</h1> <button v-on:click="getHockeyData">Get Team Data< ...

Having trouble analyzing imports in Laravel VueJs Vite due to invalid JS syntax in the content? Consider installing @vitejs/plugin-vue to help with import analysis

While incorporating vite into my laravel project, I encountered errors during the execution of npm run build, despite having correct syntax. - The issue with my component: https://i.stack.imgur.com/u0BuJ.png - My vite.config.js setup: https://i.stack.img ...

Center text inside a d3 svg element

As a newcomer to the d3 library, I am facing challenges with a basic task. Inspired by this example on gradients, I have integrated a linear gradient into the footer div element: #footer { position: absolute; z-index: 10; bottom: 10 ...

What is the proper way to deploy a Vue App after it has been built?

After deploying my Vue App on a hosting platform, I noticed an issue. When I try to access "www.mydomain.com/about" directly in the browser, I receive a 404 Error Page. This made me wonder if I deployed the wrong thing. I ran npm run build before deployin ...

How can I change the hover color of the navigation bar buttons in the Bootstrap freelancer template?

Having an issue with the hover color of the main navigation button menu while using the official freelancer template: https://github.com/BlackrockDigital/startbootstrap-freelancer The main button is displayed on narrower screens and should have a hover c ...

Creating a collapsing drop down menu with CSS

I utilized a code snippet that I found on the following website: Modifications were made to the code as shown below: <div class="col-md-12"> ... </div> However, after rearranging the form tag, the drop-down menu collapse ...

JavaScript has the ability to sort tables using tags

I am currently working on a Vue project where I am attempting to filter my table based on the tags that users click. I have created a method that outputs all the rows containing the tag clicked by the user. <el-table-column prop="Keyword" labe ...