How to implement dynamic color for classes in a v-for loop using Vue.js?

Struggling with a seemingly simple issue that may be easy for VueJS pros.

In my data, I have JSON objects with an attribute that can take values of 10, 20, 30, or 40. Depending on this value, I want to change the color of a v-btn.

I've attempted multiple methods but keep running into errors.

Here's one attempt:

<v-btn
    class="flex-column pa-6" 
    :class="getColor(item.type)"
>

where the getColor method is defined as follows:

getColor: function(type)
        {
          return this.color[type]
        }

Another approach I tried was:

<v-btn
    class="flex-column pa-6" 
    v-bind:class= "[item.type == '10' ?  color['10'] : color['20'] ]"
>

This works, however, it always defaults to color['20']. Why isn't my condition working correctly?

The v-for loop in question looks like this:

<v-card
        v-for="incident in incidents"
        :key="incident"
        class="mx-auto" 
      >

Answer №1

Here is a possible solution based on the information you provided:

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data() {
    return {
      incidents: [{type: 10, name: 'aaa'}, {type: 40, name: 'bbb'}, {type: 30, name: 'ccc'}],
      colors: [{id: 10, color: 'purple'}, {id: 20, color: 'blue'}, {id: 30, color: 'green'}, {id: 40, color: 'red'}]
    }
  },
  methods: {
    getColor(id) {
      return this.colors.find(c => c.id === id)?.color || ''
    }
  }
})
.blue {
  background-color: blue;
}
.purple {
  background-color: purple;
}
.green {
  background-color: green;
}
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/@mdi/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e88e87869ca8dec690">[email protected]</a>/css/materialdesignicons.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4a3c3f2f3e232c330a786432">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
<div id="app">
  <v-app>
    <v-main>
      <v-container>
        <v-card
          v-for="(incident, i) in incidents"
          :key="i"
          class="mx-auto" 
        >
          <v-btn
            class="flex-column pa-6" 
            :class= "getColor(incident.type)"
          >
            {{ incident.name }}
          </v-btn>
        </v-card>
      </v-container>
    </v-main>
  </v-app>
</div>

<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="196f6c7c592b3761">[email protected]</a>/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="32444757465b544b72001c4a">[email protected]</a>/dist/vuetify.js"></script>

Answer №2

Great job with your code! One thing to note is that you should consider using the !important declaration in the styles to successfully override the default style of v-btn.

Here's a Working Demo :

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data() {
    return {
      items: [{type: 10}, {type: 40}, {type: 30}],
      color: {
        10: 'purple',
        40: 'blue',
        30: 'green'
      }
    }
  },
  methods: {
    getColor(type) {
      return this.color[type]
    }
  }
})
.blue {
  background-color: blue !important;
}
.purple {
  background-color: purple !important;
}
.green {
  background-color: green !important;
}
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="89fffcecfde0eff0c9bba7f1">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8cfaf9e9ccbea2f4">[email protected]</a>/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f5838090819c938cb5c7db8d">[email protected]</a>/dist/vuetify.js"></script>
<div id="app">
  <div v-for="(item, index) in items" :key="index">
    <v-btn v-bind:class="getColor(item.type)">
     {{ getColor(item.type) }}
    </v-btn>
    <br><br>
  </div>
</div>

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

Switch a div to a computed location

I'm having trouble getting this code to animate a div to a calculated position. Can someone please help me troubleshoot? $(document).ready(function() { var is_Clicked = false; $("#togglebutton").click(function() { if (is_Cli ...

Using jQuery to select a div element that has been dynamically loaded using ajax, or inserted into the DOM using the html()

Greetings from a newcomer to stackoverflow! After searching for similar questions and answers, I still couldn't find a solution to my specific problem. Here's the situation: I have a webpage that uses ajax to load main content. The function for ...

Why is React's nested routing failing to render properly?

click here for image portrayal I am currently attempting to integrate react router, specifically a nested router. However, when I click the links on the contact page, no results are being displayed. Any assistance would be greatly appreciated. For more in ...

JSON API WebConnector for Tableau

After creating a tableau webconnector to extract data from an internal API, I used earthquakeUSGS.html as a reference (https://github.com/tableau/webdataconnector). The API responds with json data (see code below). Utilizing the "Web data connector simulat ...

Displaying Data in a Table

In my current setup, I have a table that receives data from a form through JavaScript. The code is as follows: <div class="row"> <div class="span*"> <table id="production" class="table table-bordered" style="margin:10px auto;bor ...

Single input results in array output

I have a pair of items in this array list. $.each(data.recalls,function(i) { var recall = data.recalls[i].nnaId; var description = data.recalls[i].remedyDescription; console.log(recall); console.log(description); $('textarea[name= ...

Add the AJAX response to the dropdown menu options

Currently in my project, I am utilizing Laravel as a backend. The scenario is such that once the corresponding page loads, it triggers an ajax request to fetch vehicle data which consists of vehicle model and plate number properties. My aim is to display t ...

Determine if the object's value is present

My current JavaScript setup looks like this: var NAMES = []; function INFO(id,first,middle,last){ var newMap = {}; newMap[id] = [first, middle, last]; return newMap ; } Next, I have the following code block: for (var j = 0; j < NUMBER.leng ...

What is the best way to show a pop-up model at the bottom of a webpage?

I am working on a project that involves a popup modal that needs to appear after 10 seconds. However, the issue I am facing is that the modal is currently displaying at the top of the page, but I would like it to be shown at the bottom of the page just abo ...

Selecting the first li element using JQuery selectors

Can anyone help me with creating an onclick event that triggers when the user clicks on the first list item which is labeled as "Any Date"? I am looking to use jQuery to target this specific element. <ul id="ui-id-1" class="ui-menu ui-widget ui-widge ...

"Using Angular's NgFor directive to efficiently organize and collapse data within

I am currently working on displaying API data in a table using ngFor, and I am facing an issue with hiding/showing a specific row of details outside the ngFor loop. Since this line is not within the ngFor loop, I am unable to bind the data accordingly. Can ...

Increase the number of button groups when clicked

I have a button group with three buttons: left, middle, and right. I want to enhance this functionality so that when any of the main buttons are clicked, the corresponding sub-buttons (left-sub, middle-sub, or right-sub) appear accordingly: <div class= ...

Error: Unable to instantiate a THREE.Scene object in Three.js due to TypeError

Recently, I decided to experiment with Three.js in order to incorporate it into a project of mine. However, upon running the initial example provided in the documentation: <html> <head> <title>My first Three.js app</title& ...

Using Vue.js to dynamically load a component from another component in JavaScript when the page is first loaded

As a beginner in Vue.js, I kindly request your patience. I am attempting to create a page with a Vue.js component that will contain other child components. While I have successfully created and loaded the first outer component, I am encountering difficult ...

A guide on showcasing nested arrays data in an Angular application

info = [ { list: [ { title: 'apple'} ] }, { list: [ { title: 'banana'} ] } ] My goal here is to extract the list items. Here is how they are structured. desired r ...

Elements recognized worldwide, Typescript, and a glitch specific to Safari?

Consider a scenario where you have a select element structured like this: <select id="Stooge" name="Stooge"> <option value="0">Moe</option> <option value="1">Larry</option> <option value="2">Curly</option ...

After removing an item from the array, React fails to display the updated render

As a newcomer, I am struggling with a particular issue. I have implemented a delete button for each item in a list. When the button is clicked, the object in the firstItems array is successfully deleted (as confirmed by logging the array to the console), b ...

Nuxt - Vue - Utilizing middleware on a layout in a few simple steps

Recently, I developed a middleware for authentication in my Nuxt application and now I want to utilize it within a layout. However, when trying to call the middleware using the following code: export default { middleware: 'auth', I encounte ...

Error in Node: JSON parse failure due to invalid token "'<'" and ""<!DOCTYPE ""

Every time I attempt to run node commands or create a new Angular project, I encounter the following error. Node version 20.11.0 NPM version 10.2.4 https://i.sstatic.net/Dg6BU.png https://i.sstatic.net/ZwN1Q.png ...

JavaScript code to generate a UTF8 string from UTF codes

I am in possession of the byte representation of UTF8, such as: 195, 156 for "Ü" (capital U Umlaut) I am struggling to generate a JavaScript-compatible string from these numbers - all my attempts have been unsuccessful. Every method I have tried has mis ...