Skip to content
Advertisement

Change text color in BootstrapVue table if this column value is greater than another column value

I have a BootstrapVue table that looks like this;

enter image description here

I would like to change the text colour of the number in Age column to green if Age >= ID and to red if Age < ID.

Here is the code in a single HTML file.

<link href="https://unpkg.com/bootstrap@4.4.1/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://unpkg.com/bootstrap-vue@2.2.2/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/bootstrap-vue@2.2.2/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>

I am using Vue.js v2 and BootstrapVue.

Advertisement

Answer

You can simply achieve it by using _cellVariants property.

Working Demo :

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/vue@2.6.12/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/bootstrap@4.5.3/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>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement