【问题标题】:how to sort date columns in bootstrap-vue if using formatter for displaying?如果使用格式化程序进行显示,如何在 bootstrap-vue 中对日期列进行排序?
【发布时间】:2019-11-25 14:09:26
【问题描述】:

我有一个包含日期对象的表格,我将其转换为如下所示:

{
   key: "date",
   formatter: (value, key, item) => {
     return moment(value).format("L");
   },
   sortable: true
}

这会破坏排序功能,因为它是本地化字符串。 我想做类似的事情

 sortingKey: value=>value

要覆盖呈现日期的字符串排序并返回按日期排序,但我找不到类似的东西。

更新: 这已经解决了,但对我来说,解决方案并不漂亮。一个更漂亮的解决方案是:

field: {
  key: 'date',
  sorter: (value, item, fieldMeta) => {
    // returns something that reacts to <
    // key == fieldMeta.key
    // default (current) implementation
    return fieldMeta.formatter ? fieldMeta.formatter(value, fieldMeta.key, item) : value;
  }

【问题讨论】:

    标签: javascript vue.js bootstrap-vue


    【解决方案1】:

    就我而言,我需要做的就是将sortByFormatted: true 添加到特定字段:

    {
      key: 'name',
      sortable: true,
      sortByFormatted: true,
      formatter: (value, key, item) => {
        return item.first_name + ' ' + item.last_name;
      },
    },
    

    【讨论】:

    • 顺便说一句,这里使用的是bootstrap-vue 2.0.0
    【解决方案2】:

    sort-compare 函数将成为您的恶魔。基本的排序比较方法比较两个值,并且至少需要三个参数:项目a、项目b,以及正在排序的字段key。注意ab 是被比较的整个行数据对象。

    对于上述示例,请执行以下操作:

    export default {
      // ...
      methods: {
        mySortCompare(a, b, key) {
          if (key === 'date') {
            // Assuming the date field is a `Date` object, subtraction
            // works on the date serial number (epoch value)
            return a[key] - b[key]
          } else {
            // Let b-table handle sorting other fields (other than `date` field)
            return false
          }
        }
      }
      // ...
    }
    
    <b-table :items="items" :fields="fields" :sort-compare="mySortCompare">
      <!-- ... -->
    </b-table>
    

    【讨论】:

    • 我不喜欢硬编码,但我想没有其他选择,因为字段元数据不可用。不过,这可以解决问题。
    • function 添加到字段定义与提供function sort-compare route 没有什么不同。您必须在某处添加代码。
    • 是的,不同之处在于您在使用它的地方。将键名硬编码在其他地方并不是一个理想的设计,如果您有 3 个具有此要求的字段,那么您有一个很好的 if 级联,但读起来并不好。它只是使代码混乱,它会工作,但好的是不同的东西。想想你的例子中的 return false ,你需要有评论,因为从上下文中是无法理解的。这很实用,但不是很好。
    【解决方案3】:

    我相信你需要的道具是sort-compare

    https://bootstrap-vue.js.org/docs/components/table#sort-compare-routine

    你可以在源代码中看到它是如何使用的:

    https://github.com/bootstrap-vue/bootstrap-vue/blob/a660dc518246167aa99cd3cac16b5f8bc0055f2d/src/components/table/helpers/mixin-sorting.js#L85

    它是为整个表配置的,而不是为单个列配置的。对于应该只使用默认排序顺序的列,您可以返回 undefinednullfalse,这应该会导致它回退到默认排序顺序(参见第 104 到 107 行)。

    【讨论】:

    • 谢谢。我在文档中监督了返回“后备”功能。仍然不漂亮,但它有效。
    猜你喜欢
    • 2018-01-19
    • 2011-11-19
    • 2021-05-08
    • 2012-05-03
    • 2020-01-15
    • 2023-03-14
    • 2023-02-10
    • 1970-01-01
    • 2021-12-22
    相关资源
    最近更新 更多