I am having trouble getting my getColor() method to correctly change colors based on the data provided

When using a datatable, there are two columns: status and priority. The STATUS LIST includes OPEN or CLOSED, while the PRIORITY LIST includes HIGH, MODERATE, and LOW. So, if the status is open, it should be displayed in red color; if closed, then in green. In the priority column, high priority should display in dark blue, low priority as warning color, and moderate priority as info color.

[![enter image description here][1]][1]

Currently, the colors for the Status column are displaying correctly, but the Priority column is not working as expected.

Here is the HTML template:

<v-data-table
  :headers="headers"
  :items="searchFilterArray"
  disable-pagination
  :hide-default-footer="true"
>
           
    <template v-slot:item.status="{ item }">
      <span :class="getColor(item.status)">
        {{ item.status }} // status can be open or closed
      </span>
    </template>
    <template v-slot:item.priority="{ item }">
      <span :class="getColor(item.priority)">
        {{ item.priority }} // priority can be High,Moderate or Low
      </span>
    </template>
</v-data-table>
 methods: {
    getColor (status) {
      console.log('status is : ', status) // Only open and closed are printed in the console. Not sure why Low and High are not displaying as shown in the screenshot.
      if (status === 'closed') return 'v-green font-weight-bold'
      else if (status === 'open') return 'v-error font-weight-bold'
      else if (status === 'High') return 'v-darkblue font-weight-bold'
      else if (status === 'Low') return 'v-warning font-weight-bold'
      else if (status === 'Moderate') return 'v-info font-weight-bold'
      else return 'v-secondary '
    },
 }

Answer №1

If you pass an object containing your conditions, you can simplify the process:

getColor (status) {
    return {
      'v-green font-weight-bold': status === 'closed',
      'v-error font-weight-bold': status === 'open',
      'v-darkblue font-weight-bold': status === 'High',
      'v-warning font-weight-bold': status === 'Low',
      'v-info font-weight-bold': status === 'Moderate',
      // Consider being more specific here with additional conditions 
      // such as using 
      // !['closed', 'open', 'High', 'Low', 'Moderate'].includes(status)
      'v-secondary': !status
    }
}

You don't have to use if/else statements to return the correct classes manually, vue will handle it based on boolean values.


If you're not seeing the expected output in the console.log, it may be due to a slot issue. Make sure your slot is actually being utilized.

Also, ensure that your column is correctly named priority and matches the field in the object. The header name may differ from the actual field name, causing discrepancies.


If your field is priority.name, adjust your template accordingly:

<template v-slot:item.priority.name="{ item }">
  <span :class="getColor(item.priority.name)">
    {{ item.priority.name }} // priority can be High,Moderate or Low
  </span>
</template>

The issue might be that your slot doesn't correspond with the field name, preventing vuetify from calling it properly.

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

Increasing the token size in the Metaplex Auction House CLI for selling items

Utilizing the Metaplex Auction House CLI (ah-cli) latest version (commit 472973f2437ecd9cd0e730254ecdbd1e8fbbd953 from May 27 12:54:11 2022) has posed a limitation where it only allows the use of --token-size 1 and does not permit the creation of auction s ...

What are the best ways to conceptualize the benefits of WebRTC?

I encountered a peculiar issue with the abstraction of the WebRTC offer generation process. It appears that the incoming ice candidates fail to reach the null candidate. While I have been able to generate offers successfully using similar code in the past, ...

Ensuring React's setupProxy functions properly in conjunction with express.js

I've encountered an issue while trying to pass images from express to react. My express.static is correctly set up, so when I visit localhost:5000/public/images/me.jpeg, the image loads in my browser. However, when I attempt to use <img src="/publi ...

Guide on efficiently inserting values into an array of objects

I'm looking to extract specific values from the enum below enum p { XDR = 1, PT1M = 2, PT1M_ = 2, PT5M = 3, PT5M_ = 3, PT15M = 4, PT15M_ = 4, PT1H = 5, PT1H_ = 5, P1D = 6, P1D_ = 6, P7D = 7, P1W = 7, ...

Tips for restricting the information retrieved from an API?

Currently, I am in the process of learning how to use AJAX with vanilla JS. My goal is to implement a limit on the amount of data received from an API, specifically restricting it to 10 objects maximum. The API url that I am working with can be found here ...

Is there a way to asynchronously load image src URLs in Vue.js?

Why is the image URL printing in console but not rendering to src attribute? Is there a way to achieve this using async and await in Vue.js? <div v-for="(data, key) in imgURL" :key="key"> <img :src= "fetchImage(data)" /> </div> The i ...

Personalized Element Commands and features

UniquePage.html <div ng-controller="UniquePageCtrl"> <unique-custom-directive arg1="{{currentObj.name}}"></my-custom-directive> <div> in UniquePageCtrl.js (Controller) app.controller("UniquePageCtrl", ["$scope", function ($sc ...

Enhanced data visualization with Material UI's nested datagrid feature

Is there a way to display nested JSON data on a React Material UI data grid? I'm looking to showcase the phone numbers of users from the JSON in the provided sandbox example. You can check out the demo here. ...

Send live information to router-link

I'm struggling to pass a dynamic path to vue-router, but I can't seem to get the syntax right. Here's what I've been attempting: <li v-on:click="$emit('closeDropdown')"><router-link :to="item.route" id="button">{{ ...

Issue encountered with Express.js and connect-mongo session: "TypeError - Unable to access property 'upserted' as it is undefined"

I'm working on implementing session storage using the connect-mongo module, but I keep encountering the following error: TypeError: Cannot read property 'upserted' of undefined Here is how I'm using the connect-mongo: import session ...

Angular HttpClient request fails to initiate

Overview: A button click on a form triggers the methodForm within the component. methodForm then calls methodService in the service layer. methodService is supposed to make an HTTP POST request. Problem: The HTTP POST request is not being made. However, me ...

How to redirect to a different view or controller using ASP.NET and AngularJS

How can I open the View located at /Home/CreateItem after clicking on the Add button? What do I need to include in my code? $scope.Add = function() { console.log('working'); } This is how Index.cshtml looks like: <script src="~/ ...

How can I implement a jQuery slide down effect for a specific individual instance?

Whenever I click on the "Share your thoughts" button, the comments block slides down for every section instead of just the particular section I clicked on. Is there a way to make it so that only a single block slides down when the button is clicked, regard ...

Adding an additional parameter in the ListItem onMouseOver function

Within my React code base, I have a material-ui ListItem that looks like this: <ListItem button key={currIndex} onMouseOver={handleOnMouseClickOnListItem}> The handler function in my code (using Flow typing) is as follows: const handleOnMouseClic ...

Ways to display and conceal menu depending on initial view and scrolling

On my website, I have implemented two menus - one to be displayed when the page loads and another to show up when a scroll occurs. You can view my page here. The goal is to have the white part visible when the position is at the top, and switch to the blu ...

At random intervals, a ReferenceError is triggered stating that Vue is not defined

While working on an application that uses templates rendered by Apache Velocity, I encountered the error "Uncaught ReferenceError: Vue is not defined" when trying to incorporate vue.js components. Oddly enough, this error is not consistent - it occurs most ...

How to Retrieve Checkbox Values from Multiple Rows Using JavaScript

I have a variety of module rows that allow users to manage access rights by selecting specific options. My goal now is to extract the checked boxes from these checkboxes with the name "config{{$field->id}}". Below is the current functioning code. HTM ...

Using a combination of Vue.js and AJAX to make requests within a v-for loop, all while

I have a set of data (todos array) that displays in my model, and I am rendering this data in a list. I am trying to implement a functionality on the list that whenever click on any item on the list, the selected variable's value should be updated wi ...

jQuery UI dynamically adjusting content layout based on browser size changes

Having an issue with my custom accordion script where resizing the browser causes formatting problems in one of the sections. I want the content to remain intact and to utilize a scrollbar if necessary to view the content. The problem is visible in section ...

Exploring Nested Data in MongoDB Aggregation using $match and $project

Struggling with crafting a Mongoose Aggregate Query to extract the permissions object of a specific member within a deeply nested structure of business data. MongoDB's documentation on this topic is lacking, making it hard for me to progress. Sample ...