Search code examples
javascriptvue.jsbootstrap-vue

Boostrap Vue Change Cell Text in B-table


In a b-table, each cell in a column should have different text color. Not the background of the cell, but the actual text color. I am able to change the text color of the column header, but not the individual cell texts.

The b-table code:

<b-card title="Total">
  <b-table sticky-header="600px" hover :items="total" :fields="groupByFields"></b-table>
</b-card>

The fields where the column header color change is:

groupByFields: [
    {
      key: 'name',
      sortable: true,
    },
    {
      label: 'Total',
      key: 'count',
    },
    {
      key: 'interested',
      thStyle: { color: '#3eef33' },
      sortByFormatted: false,
      formatter: (value) => {
        const res = value;
        return (`($${res})`);
      },
    },
  ],

The thStyle color attribute changes the header text color, but not the text of values in the cells of that column. How would I match that color to the cell text (not background) of that column too?


Solution

  • Here's an example, using the #cell() slot:

    new Vue({
      el: '#app',
      data: () => ({
        items: [],
        fields: [
          'id',
          { key: 'title', style: { fontStyle: 'italic' } },
          { key: 'price', style: { color: 'red', textAlign: 'right' } }
        ]
      }),
      mounted() {
        fetch('https://dummyjson.com/products')
         .then(_ => _.json())
         .then(_ => this.items = _.products);
      }
    })
    <link href="https://unpkg.com/bootstrap@4.6.1/dist/css/bootstrap.min.css" rel="stylesheet"/>
    <link href="https://unpkg.com/bootstrap-vue@2.22.0/dist/bootstrap-vue.css" rel="stylesheet"/>
    <script src="https://unpkg.com/babel-polyfill/dist/polyfill.min.js"></script>
    <script src="https://unpkg.com/vue@2.6.12/dist/vue.min.js"></script>
    <script src="https://unpkg.com/bootstrap-vue@2.22.0/dist/bootstrap-vue.js"></script>
    
    <div id="app">
      <b-table :items="items" :fields="fields">
        <template #cell()="{field, value}">
          <div :style="field.style" v-text="value" />
        </template>
      </b-table>
    </div>

    If you only need to style a few columns, you might want to use appropriate #cell({key}) slots.

    Documentation here.


    Probably the most common technique is to add classes to cells. It provides granular control over the applied styling, without sacrificing flexibility.