Arkeen
Arkeen

Reputation: 604

BootstrapVue table : sort by date and by string?

I am quite new to VueJS, and currently using BootstrapVue (latest version, v2.0.0), mostly its b-table feature. I load table items dynamically (from a JSON file), and one of my field (column) is a string, the other is a formatted date (dd/MM/YYYY). I would like be able to sort those dates like other string or number fields. The doc mention the possibility to create custom sorting function, so I wrote one (as a global function, using moment.js as suggested) :

function sortDate(a, b, key) {
  aDate = moment(a[key], 'DD/MM/YYYY')
  bDate = moment(b[key], 'DD/MM/YYYY')
  if (aDate.isValid && bDate.isValid) {
    if (aDate < bDate) {
      return -1
    }
    else if (aDate > bDate) {
      return 1
    }
    else {
      return 0
    }
  }
  return null
}

I then integrate it to HTML b-table using the :sort-compare tag :

<b-table id="bh_table" :items="items" :fields="fields" :sort-compare="sortDate"></b-table>

The problem is that the regulat string-sorting is broken, and I am not sure how to fix it ? Should I create a global method that should detect column type, and sort accordingly ?

It seems to be the thing to do here, but I think it is quite counter-intuitive, getting possible duplicates (I have other table that contains number and dates, only dates, etc.)

Upvotes: 2

Views: 3780

Answers (1)

Troy Morehouse
Troy Morehouse

Reputation: 5435

You are not checking for which key is being sorted on. Also note a and b are the entire row data.

function sortDate(a, b, key) {
  if (key !== 'myDateField') {
    // `key` is not the field that is a date.
    // Let b-table handle the sorting for other columns
    // returning null or false will tell b-table to fall back to it's
    // internal sort compare routine for fields keys other than `myDateField`
    return null // or false
  }
  aDate = moment(a[key], 'DD/MM/YYYY')
  bDate = moment(b[key], 'DD/MM/YYYY')
  if (aDate.isValid && bDate.isValid) {
    if (aDate < bDate) {
      return -1
    }
    else if (aDate > bDate) {
      return 1
    }
    else {
      return 0
    }
  }
  return null
}

Upvotes: 3

Related Questions