1
votes

I have a table that pulls information from a database using Bootstrap-vue. The database has a field called "day" which stores a string value of "mon", "tue", "wed", etc. I want to be able to sort the table by this column by day, rather than alphabetically. Is there a way to do this?

I'm pretty new to Vue and Bootstrap Vue. I've set up the table, and it pulls the information from the Database just fine. It stores each as an object, and displays it according to defined fields.

Simplified code to visualize problem:

HTML:

<div id='root'>
   <b-container fluid>
      <h1>Welcome</h1>
      <br/>
      <b-table
         show-empty
         stacked="md"
         :items="tableItems"
         :fields="fields"
         sort-by="day"
      >
      </b-table>
   </b-container>
</div>

Vue:

new Vue({
el: '#root',
data() {
   return {
      tableItems: [
         {name: 'Mark', age: '23', day:'wed'},
         {name: 'John', age: '21', day:'thu'},
         {name: 'Stephen', age: '24', day:'tue'},
         {name: 'Will', age: '31', day:'fri'},
         {name: 'Andrew', age: '27', day:'wed'},
         {name: 'James', age: '24', day:'mon'},
         {name: 'Shawn', age: '29', day:'tue'},
      ],
      fields: [
         { key: 'name', label: 'Name', sortable: true},
         { key: 'age', label: 'Age', sortable: true, class: 'text-center' },
         { key: 'day', label: 'Day', sortable: true},
      ],
      }
   }
});

Currently this code will sort alphabetically in the day column. I'd like it to sort by "date", e.g. "mon", "tue", "wed", etc

1

1 Answers

4
votes

You can use your own custom sort method by hooking into the :sort-compare routine.

  <b-table
     show-empty
     stacked="md"
     :items="tableItems"
     :fields="fields"
     :sort-compare="sortingChanged"
  >

Then define a dictionary to give your days values.

const days = {
  "sun": 0,
  "mon": 1,
  "tue": 2,
  "wed": 3,
  "thu": 4,
  "fri": 5,
  "sat": 6,
};

and finally handle the sorting.

  methods: {
    sortingChanged(a, b, key) {
      let result = 0;
      if (key === 'day') {
          let day1 = a[key].toLowerCase();
          let day2 = b[key].toLowerCase();
          return days[day1] - days[day2];
      } 
      return false;
    }
  }

The Math.min/max stuff is to clamp the value between -1 and 1 which the sort-compare routine requires to work properly.

Here's a working codesandbox example. You can read more about the sort-compare routine in the docs.

Thanks to @TroyMorehouse for pointing out a better approach.