2

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.)

1
  • 1
    If you could use moment library, it would be much easier. Commented Jun 3, 2019 at 12:58

1 Answer 1

3

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.