【问题标题】:BootstrapVue table : sort by date and by string?BootstrapVue 表:按日期和字符串排序?
【发布时间】:2019-07-17 09:37:10
【问题描述】:

我对 VueJS 很陌生,目前使用的是 BootstrapVue(最新版本,v2.0.0),主要是它的 b-table 功能。我动态加载表项(从 JSON 文件),我的字段(列)之一是字符串,另一个是格式化日期(dd/MM/YYYY)。我希望能够像其他字符串或数字字段一样对这些日期进行排序。 文档提到了to create custom sorting function 的可能性,所以我写了一个(作为全局函数,按照建议使用moment.js):

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
}

然后我使用 :sort-compare 标签将它集成到 HTML b-table 中:

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

问题是规则字符串排序被破坏了,我不知道如何修复它?我应该创建一个应该检测列类型并进行相应排序的全局方法吗?

这似乎是这里要做的事情,但我认为这很违反直觉,可能会出现重复(我有其他包含数字和日期的表,只有日期等)

【问题讨论】:

  • 如果你可以使用moment库,那就容易多了。

标签: sorting vue.js html-table bootstrap-vue


【解决方案1】:

您没有检查正在排序的键。另请注意ab 是整行数据。

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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-01
    • 1970-01-01
    • 2018-07-07
    • 1970-01-01
    • 1970-01-01
    • 2016-08-07
    • 2015-04-14
    • 2019-01-05
    相关资源
    最近更新 更多