Dynamic Configuration of Table Variants with Bootstrap-Vue

Currently, I am utilizing Bootstrap Vue in a test application. My objective is to modify the variant of a table cell based on its value. Unfortunately, the variant parameter does not accept a function, leading me to search for alternative solutions.

Listed below is my code snippet:

var app = new Vue({
    el: '#app',
    data: {    
        items: [],      //Populated via AJAX
        fields: [
        {              
            key: 'Vendedor',
            label: 'Vendedor'                 
        },       
        {              
            key: 'OBJETIVO',
            label: 'Objetivo',
            formatter: (value) => { return parseFloat(value).toFixed(2)},
            variant: estiloObjetivo //Issue with this line
        }
      ]
    },
    methods: {
        Cargar: function () {
            var salesperson = getCookie('salespersonCode');
            var url_servicio = 'http://MywebService/';
            var self = this;
            $.ajax({
                type: 'GET',
                url: url_servicio + 'ventas/' + salesperson,
                dataType: "json",                  
                success: function(data){            
                    self.items = data           
                }
            });
        },
        estiloObjetivo (value) {
                if value > 0 
                 return 'danger'
                else 
                 return 'success'

        }
    }
})

The HTML section associated with my code:

<div id="app">  
    <button v-on:click="Cargar">Cargar</button>
    <b-table striped hover :fields="fields" :items="items"></b-table>
</div>

Any suggestions on how I can dynamically style a Bootstrap-Vue cell?

In the documentation, styling is set within the "items" array. However, in scenarios like mine where data is retrieved from a web service, how can I achieve this?:

{
    salesperson: 'John',
    Objetivo: 2000,
    _cellVariants: { salesperson: 'success', Objetivo: 'danger'}
  },

Therefore, I am seeking a method to customize the _cellVariants parameter of each element in the 'items' array.

Answer №1

If you find yourself in need of a computed property, you're on the right track. Computed properties are designed to automatically update when any of the reactive variables they rely on change.

Here's an example that illustrates the implementation of a computed property called styledItems. This property should be used instead of items in your template. It creates a shallow copy of each item in the array, adding an extra property called _cellVariants.

new Vue({
      data: {
        items: [ /* your data here */ ]
      },
      methods: {
        customStyle: value => (value > 0) ? 'danger' : 'success'
      },
      computed: {
        styledItems() {
          return this.data.map(item =>
            Object.assign({}, item, {
              _cellVariants: {
                Goal: this.customStyle(item.Goal)
              }
            })
          }
        })

Answer №2

To incorporate a variant to your items, consider using a computed property named cptItems. Define it in the following manner:

computed:{
     cptItems(){
        return this.items.map((item)=>{
               let tmp=item;
                item.OBJETIVO>0?tmp.variant='danger':tmp.variant='success';
                return tmp;

        })  
        }

Then, utilize that property within your template like so:

<b-table .... :items="cptItems"></b-table>

Answer №3

Although the answers provided above didn't resolve my issue, I was able to find an alternative method for coloring table cells: https://github.com/bootstrap-vue/bootstrap-vue/issues/1793

This approach involves using tdclass and a function rather than variants to color a table cell.

<script>
  new Vue({
    el: '#itemView',
    data() {
      return {
        fields: [
          {
            key: 'Objetive',
            sortable: true,
            thClass: 'text-nowrap',
            tdClass: (value, key, item) => {
              return 'table-' + this.getColor(item);
            }
          }
        ],
      };
    },
    methods: {
      getColor(item) {
        return item.Objetive > 0 ? 'danger' : 'success';
      },
    },
  });
</script>

In my particular scenario, I needed to compare two cells in the same row and apply a class to one of them.

...
      {
        key: 'DEMAND_QTY',
        sortable: true,
        thClass: 'text-nowrap',
        tdClass: (value, key, item) => {
          return 'table-' + this.demandStatusColor(item);
        },
      },
      { key: 'TOTAL_DEMAND', sortable: true, thClass: 'text-nowrap' },
    ],
  };
},
methods: {
  demandStatusColor(item) {
    return item.DEMAND_QTY < item.TOTAL_DEMAND ? 'danger' : 'success';
  },
}
...

Perhaps this solution will benefit someone else, even if it doesn't directly help the original poster.

Answer №4

@Sarah provided a solution that worked perfectly for my situation. Unfortunately, I lack the reputation to leave comments or express gratitude.

tdStyle: (type, key, item) => {
        switch (type) {
          case "value1":
            return "bg-warning text-white";
            break;
          case "value2":
            return "bg-danger text-white";
            break;
          case "value3":
            return "bg-info text-white";
            break;
          default:
            break;
        }
      },

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

Executing a function to erase the stored value in local storage during an Angular unit test

Looking to verify whether the localStorage gets cleared when I execute my function. Component ngOnInit() { // Logging out when reaching login screen for login purposes this.authService.logout(); } authService logout() { // Removing logged i ...

Adjust Javascript Code to Modify Speed of Sine Wave Live

Feeling a bit lost here, but I need some assistance with a simple task. I'm trying to adjust the speed of a sine wave from 2 to 10 when a button is clicked. It seems like a small change, but for some reason, I can't quite figure it out. If you& ...

Having issues with dynamic router links on vue.js -- any suggestions?

Why is my page not loading properly when clicked on a router-link? When I click on each link, it displays correctly in the address bar but the page does not load or route. However, if I refresh the page, it then shows the correct content. [routes] ` imp ...

Learn the process of creating a webpage that is accessible to users who are signed in through Parse

I created a landing page where users can easily login or register using parseSDK. This feature is currently working well. The next step was building a dashboard page (dashboard.html) that should only be accessible to logged-in users. However, I noticed tha ...

The RXJS Scan operator is sending out a lone element

I've been experimenting with the RXJS scan operator, but I'm struggling to understand it fully. My goal is to make the scan operator not return the accumulated result, but rather the emitted items from the source if bufferResults is set to false. ...

Responsive navbar in Bootstrap collapses and closes again after opening on a small screen

Although the navbar functions properly on larger screens, it collapses back after pressing the collapse icon when viewed on a mobile screen. <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charse ...

What are the steps to limit the usage of angular.module('myApp', ['ngGrid', 'ui.bootstrap', 'kendo.directives'])?

I have two JavaScript files with AngularJS code. The first file, myjs1.js, includes the module: angular.module('myApp', [ 'ngGrid', 'ui.bootstrap', 'kendo.directives' ]); The second file, myjs2.js, also includes th ...

Managing iframes in React using reference methods

Trying to set the content of an iframe within a React component can be a bit tricky. There is a component that contains a handleStatementPrint function which needs to be called when the iframe finishes loading. The goal is to print the loaded iframe conten ...

What is the best way to have DOMDocument processed in PHP after running Javascript?

Currently, I'm working on a program that searches for tags. Unfortunately, I'm encountering difficulties retrieving tags created with JavaScript. ...

Inform the PHP backend that the browser has been closed by the frontend Angular application

Currently, I am working on an Angular project that is interacting with a backend project created using PHP and ZF3. I am trying to figure out the most efficient method of informing the backend project when the user closes the browser window. Initially, I ...

What are the steps to change the rendering order of Vue components in mobile view?

I have implemented 2 Vue components that split the page into two sections: left side and right side. These components are utilized on every page with the following structure: <template> <div class="page-body"> <left-side> < ...

Can an ongoing asynchronous call be canceled regardless of its current status?

As I enter text into my textfield widget, a request is sent to the server with every character typed in order to retrieve matching data. However, when I type rapidly, the server gets swamped with requests causing my control to freeze. To address this issu ...

Create a JSON object in JavaScript that will specifically retrieve and return only the values where the value exists

These are the specific objects I am working with: {"event":"auth success"} {"event":"status","args":["running"]} {"event":"console output","args":["openjdk versi ...

Scroll to the next list group item and align the content in the center when viewing on mobile devices using React

1) I need help with implementing auto scrolling to the next item in a list group. Specifically, when a user answers the first question, it should automatically scroll to the second question (using React). Additionally, upon submitting the form, it should s ...

Find and conceal the object within the list that includes the term "Ice"

The teacher's assignment is to create a radio button filter that hides items with the word "Ice" in them, such as "Ice Cream" and "Iced Tea." Here is the current code I have been working on: <!DOCTYPE html> <html> <head> <me ...

What is the reason behind only the initial click boosting the vote count while subsequent clicks do not have the same

In this snippet of code: //JS part echo "<script> function increasevotes(e,location,user,date,vote) { e.preventDefault(); var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState ...

Accessing Django ManyToManyField via Ajax using its ID

Here are my models: class Topping(models.Model): name=models.CharField(max_length=24) class Pizza(models.Model): toppings=models.ManyToManyField(Topping) Now, onto the views: def get_pizza(request): if request.is_ajax(): pizza_list= ...

Adding data to a Vue.JS array from an HTML source

I'm facing a challenge with my assignment where I am struggling to input data from HTML into the VUE.JS array. I have created this form, and now I need assistance in updating the Students array in Vue.js when a user completes the form and clicks on th ...

The functionality of OnMouseOver event within CKEditor

I prefer using the CKEditor WYSIWYG editor. One issue I have encountered is with a div element that includes an onMouseOver attribute. When this element is within the editor, the onMouseOver attribute gets changed to data-cke-pa-onmouseover. Despite my eff ...

Discovering the selected href URL using JQuery or JavaScript

How can I detect the clicked href URL using JQuery when no ID is being used? For example, if I have a list of links where some redirect to new pages and others call javascript functions to expand a div. What approach should be taken in JQuery/Javascript ...