Modify the text color of a column in a BootstrapVue table if its value exceeds that of another column

Looking to customize my BootstrapVue table

https://i.sstatic.net/x20Si.png

Seeking advice on changing text color based on conditions in the Age column

Check out the HTML code below

<link href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="76141919020502041706364258425847">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="30525f5f4443444251401d46455570021e021e02">[email protected]</a>/dist/bootstrap-vue.css" rel="stylesheet"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a0c2cfcfd4d3d4d2c1d08dd6d5c5e0928e928e92">[email protected]</a>/dist/bootstrap-vue.min.js"></script>

<div id='app'>
    <b-table :items="items" :fields="fields" bordered>  
    </b-table>
</div>

<script>
    new Vue({
  el: '#app',
  data: dataInit,  
})

function dataInit() {  
    
    let init_data = {};
    
    init_data.fields = [
        { key: 'id', label: 'ID'},
        { key: 'age', label: 'Age'},
        { key: 'first', label: 'First Name'},
        { key: 'last', label: 'Last Name'},        
      ];
    init_data.items = [
        { id: 18, first: 'Mike', last: 'Kristensen', age: 16 },
        { id: 40, first: 'Peter', last: 'Madsen', age: 52 },
        { id: 80, first: 'Mads', last: 'Mikkelsen', age: 76 },
        { id: 28, first: 'Mikkel', last: 'Hansen', age: 34 },
      ];
    
    return init_data;
  }
</script>

Utilizing Vue.js v2 and BootstrapVue for this project.

Answer №1

You can easily accomplish this by utilizing the _cellVariants property.

Example in Action :

new Vue({
    el: '#app',
    data() {
      return {
        items: [{
          id: 18,
          age: 16,
          first_name: 'Dickerson',
          last_name: 'Macdonald'
        },
        {
          id: 40,
          age: 52,
          first_name: 'Larsen',
          last_name: 'Shaw'
        },
        {
          id: 80,
          age: 76,
          first_name: 'Geneva',
          last_name: 'Wilson',
        },
        {
          id: 28,
          age: 34,
          first_name: 'Thor',
          last_name: 'MacDonald'
        }]
      }
    }
  })
.text-red {
  color: red;
}

.text-green {
  color: green;
}
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="097f7c6c493b273f27383b">[email protected]</a>/dist/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-vue/2.21.2/bootstrap-vue.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-vue/2.21.2/bootstrap-vue.min.css"/>
<link rel="stylesheet" href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="92f0fdfde6e1e6e0f3e2d2a6bca7bca1">[email protected]</a>/dist/css/bootstrap.min.css"/>
<div id="app">
  <b-table hover :items="items">
    <template v-slot:cell(age)="{ item }">
      <span :class="{ 'text-green': item.age >= item.id, 'text-red': item.age < item.id }">
      {{ item.age }}
      </span>
    </template>
  </b-table>
</div>

Answer №2

You have the option to implement the method demonstrated here.

This involves using the tdClass property within your field definition, which allows for a function that can conditionally return a class or classes. The function will receive the following arguments:

  • value, representing the raw value in the cell.
  • key, corresponding to the field key.
  • item, referring to the entire object for each row, enabling access to other cell values.

new Vue({
  el:"#app",
  data: () => ({
    fields: [
      { key: 'last_name' },
      { key: 'first_name' },
      { 
        key: 'age', 
        label: 'Person age',
        tdClass: (value, key, item) => value >= item.id ? 'text-success' : 'text-danger'
      }
    ],
    items: [
      { id: 18, age: 40, first_name: 'Dickerson', last_name: 'Macdonald' },
      { id: 50, age: 11, first_name: 'Larsen', last_name: 'Shaw' },
      { id: 87, age: 89, first_name: 'Geneva', last_name: 'Wilson' },
      { id: 66, age: 38, first_name: 'Jami', last_name: 'Carney' }
    ]
  })
});
<link type="text/css" rel="stylesheet" href="//unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f99b96968d8a8d8b9889b9cdd7ccd7ca">[email protected]</a>/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="//unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1d7f7272696e696f7c6d306b68785d2f332f2c332f">[email protected]</a>/dist/bootstrap-vue.css" />

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.12/vue.min.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9cfef3f3e8efe8eefdecb1eae9f9dcaeb2aeadb2ae">[email protected]</a>/dist/bootstrap-vue.js"></script>


<div id="app" class="p-3">
  <b-table striped hover :items="items" :fields="fields"></b-table>
</div>

Answer №3

One way to dynamically style rows in a table is by using the BootstrapVue prop ":tbody-tr-class". You can create a method that checks if the age is greater than 18 and apply the bootstrap danger class to turn the row red.
For more information on Row Styling and attributes, refer to this link: . Here's an example of how you can achieve this:

<link href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e88a87879c9b9c9a8998a8dcc6dcc6d9">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ccaea3a3b8bfb8beadbce1bab9a98cfee2fee2fe">[email protected]</a>/dist/bootstrap-vue.css" rel="stylesheet"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7e1c11110a0d0a0c1f0e53080b1b3e4c504c504c">[email protected]</a>/dist/bootstrap-vue.min.js"></script>

<div id='app'>
    <b-table :items="items" :fields="fields"  bordered>  
    <template #cell(age)="data"> <span v-if="data.item.age>18" class="text-danger">{{ data.item.age }}</span> <span v-else>{{ data.item.age }}</span> </template>
    </b-table>
</div>

<script>
    new Vue({
  el: '#app',
  data: dataInit,  
  
})

function dataInit() {  
    
    let init_data = {};
    
    init_data.fields = [
        { key: 'id', label: 'ID'},
        { key: 'age', label: 'Age'},
        { key: 'first', label: 'First Name'},
        { key: 'last', label: 'Last Name'},        
      ];
    init_data.items = [
        { id: 18, first: 'Mike', last: 'Kristensen', age: 16 },
        { id: 40, first: 'Peter', last: 'Madsen', age: 52 },
        { id: 80, first: 'Mads', last: 'Mikkelsen', age: 76 },
        { id: 28, first: 'Mikkel', last: 'Hansen', age: 34 },
      ];
    
    return init_data;
  }
</script>

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

Trouble encountered while trying to utilize a Promise to define a global variable

I am attempting to populate a global variable using a function and then call subsequent functions after the data is retrieved. Below is the current code I have: $(function () { var jsonData = {}; var dataRetrievalPromise = function () { r ...

What determines why the input value is restricted to being of type string?

In my ReactJS component, I am struggling to set the state value as an integer using setState. This is causing issues with the radio button not being checked. constructor(props) { super(props); this.state = { frequency: 1, } handleSelectChange(eve ...

Angular Karma encountered an error: TypeError - It is unable to read the property '_id' as it is undefined

Encountering an issue while testing with karma jasmine, the error message appears as... TypeError: Cannot read property '_id' of undefined This is the Component.ts file: import { Component, OnInit } from '@angular/core'; import { ApiSe ...

Retrieving results from a Node.js application that utilizes multithreading

A new function called diversify() has been developed to execute an expensive function f() in parallel on all the cores of the machine in which it is being deployed. Additionally, a mechanism has been implemented so that when f() returns a value on one core ...

What is the best way to eliminate a trailing backslash from a string?

Currently, I am iterating through a list of Discord server names in node.js. The goal is to create a php file that contains an array structured like this: <?php $guildLookup = array( "164930842483761" => "guildName1", "56334 ...

What is the best way to retrieve state within a property of a React class component?

I have encountered an issue with a React Class Component where I am trying to separate a part of the rendered JSX but unable to access the Component's state within the separated JSX as a property of the class. The scenario is quite similar to the fol ...

Crafting LayerGroups on the Fly with Leaflet

Dynamic Creation of LayerGroups: Is it Achievable? I am currently working on a web map showcasing the various tree species present in parks. My goal is to create a separate LayerGroup for each species so that users can toggle visibility using a LayerContro ...

It appears that the jQuery this() function is not functioning as expected

Despite all aspects of my simple form and validation working flawlessly, I am facing an issue where 'this' is referencing something unknown to me: $('#contact').validator().submit(function(e){ e.preventDefault(); $.ajax ...

Employ the fetch method to perform a get request along with a data object

In my current project, I am utilizing the Fetch API and I am looking to streamline the process by creating a function that can handle various parameters like method, url, and data in order to create the appropriate request for both GET and POST methods. I ...

What are the steps to conducting a search on mongodb?

My document list is shown below [{"userId": "1", "text": "National security is of utmost importance"}, {"userId": "2", "text": "We must ensure a strong defense while upholding civil ...

The keyboard fails to open when trying to input text on a WKWebView

Is there a way to programmatically open the keyboard in a WkWebView for tel text input after a JavaScript function call? I want the keyboard to display for efficiency reasons when a certain input is activated, but it doesn't gain focus automatically. ...

How can I use an array to dynamically populate an option html tag in react?

I am attempting to populate an option in jsx with values from an array called currencyOptions. Despite using this method, the options are remaining blank. The array is passed down to the component as a prop, set using useState, and the data is fetched from ...

Retrieve the product IDs by selecting the checkboxes, then compile a fresh array consisting of the identified IDs

I am currently delving into the realm of typescript/angular2+ as a fledgling student, and I have taken on the task of creating a website to put my newfound knowledge to the test. The view is up and running, but I'm facing some roadblocks as I work on ...

Creating a preloading animation for a Vue.js single-page application using svg illustrations

Looking to enhance my vue.js SPA application by incorporating a preloading animation using SVG and a progress bar. I want to keep users engaged with an animation while background files are loading, similar to the loading animations on Gmail or https://js ...

A step-by-step guide to installing a JavaScript package from GitHub

As I continue to improve my skills in JavaScript, I am eager to start using new packages. One that has caught my attention is this customizable Organisational Chart Plugin With jQuery OrgChart which can be found at https://www.jqueryscript.net/chart-graph/ ...

Want to automatically redirect the home page? Here's how!

I am trying to automatically redirect the home page after clicking the update button. Below is the code for my handleSubmit function: const handleSubmit = (e) => { e.preventDefault(); // retrieving data from the backend axios .put(`${ ...

Develop a toggle button feature that allows users to hide or reveal a specific div on

My goal is to implement a button with specific behavior: 1) Initially, the List View is displayed as default 2) When the user clicks on the button labeled Card View, the List View is hidden and the Card View is shown. The classes for these views are set ...

Design a directive for universal use in both models and controllers

Throughout my app, there is a consistent functionality where users can input a title and link. I decided to create a directive for this. However, the directive needs to be utilized in various controller contexts. For instance, in the /contracts view, the ...

There appears to be a missing value in the array for IndexOf function

Why is my IndexOf function returning -1 when I know the value is in the array? This issue has been confirmed with console.log using the following code (paraphrased for simplicity): var xtiles = []; function assignValue(tile) { xtiles.push(tile); //t ...

I'm curious about how the OAuth protocol handles the return of parameters after the # symbol in the oauth_callback

Implement the single sign-on feature in the project using the OAuth protocol. However, the project is being redirected by Vue's routing system and requires the ability to jump to a specific page after the '#' symbol in the URL. It seems that ...