Search code examples
vue.jsbootstrap-vue

Vue Bootstrap Table add different classes to columns


I'm using a Vue Bootstrap Table component and I want to add different CSS classes to different columns. I want my first column to have text-left, all the others text-center and the last one (right end one) to have text-right. Here is the current version of the b-table;

    <div class="table-responsive mb-0">
      <b-table
        :items="tableData"
        :fields="displayColumn"
        responsive="sm"
        :per-page="perPage"
        :current-page="currentPage"
        :sort-by.sync="sortBy"
        :sort-desc.sync="sortDesc"
        :filter="filter"
        :filter-included-fields="filterOn"
        @filtered="onFiltered"
        hover
      >
    <template #cell(detail)="row">
      <button @click="toggleRightBar(); changeRightBarContent(row.index)" class="btn btn-outline-primary toggle-right">
        <i class="bx bx-detail toggle-right"></i>
      </button>
    </template>
      </b-table>

Is there any way to add classes to specific columns or rows? Thanks in advance.


Solution

  • You can configure a class on your td column using the tdClass property on your fields list. Here is a link to a working fiddle

    Relevant code:

    new Vue({
        el: '#app',
          data() {
            return {
              // Note 'isActive' is left out and will not appear in the rendered table
              fields: [
                {
                  key: 'last_name',
                  sortable: true
                },
                {
                  key: 'first_name',
                  sortable: false
                },
                {
                  key: 'age',
                  label: 'Person age',
                  sortable: true,
                  // 'my-class' will be applied to all the <td> elements for this column
                  tdClass: 'my-class'
                }
              ],
              items: [
                { isActive: true, age: 40, first_name: 'Dickerson', last_name: 'Macdonald' },
                { isActive: false, age: 21, first_name: 'Larsen', last_name: 'Shaw' },
                { isActive: false, age: 89, first_name: 'Geneva', last_name: 'Wilson' },
                { isActive: true, age: 38, first_name: 'Jami', last_name: 'Carney' }
              ]
            }
          }
        })
    
    <div id="app">
      <div>
          <b-table striped hover :items="items" :fields="fields"></b-table>
        </div>
    </div>
    

    Read more at the docs: https://bootstrap-vue.org/docs/components/table#field-definition-reference