簡體   English   中英

通過升序和降序切換 lodash order

[英]Toggle lodash orderBy ascending and descending

我的 vue.js 中有一個方法,它按我的項目按升序注冊的日期對我的項目進行排序,但我真正想要的是單擊 1 個唯一按鈕並在升序和降序之間切換。

JS

sortAsc(customers) {
  // Click and sort registered customers by ascending
  let sort = _.orderBy(this.customers, 'registered', 'asc')
  this.sortedCustomers = sort
}

當我按升序單擊 1x 排序並按降序單擊 2x 排序時,如何進行上述操作?

謝謝

向保存當前排序順序的 object ( sortOrder ) 添加另一個屬性。 當您調用 function 時切換它 - 如果它undefined或設置為desc則使用asc

sortAsc(customers) {
  this.sortOrder = this.sortOrder !== 'asc' ? 'asc' : 'desc'

  const sort = _.orderBy(this.customers, 'registered', this.sortOrder)
  this.sortedCustomers = sort
}

您可以使用.sortBy ,它總是會返回一個升序列表:

_.sortBy([2, 3, 1], function(num) {
    return num;
}); // [1, 2, 3]

但是您可以使用.reverse方法使其降序:

var array = _.sortBy([2, 3, 1], function(num) {
    return num;
});

console.log(array); // [1, 2, 3]
console.log(array.reverse()); // [3, 2, 1]

或者在處理數字時,在返回中添加一個負號以降低列表:

_.sortBy([-3, -2, 2, 3, 1, 0, -1], function(num) {
    return -num;
}); // [3, 2, 1, 0, -1, -2, -3]

在 hood.sortBy 使用內置的.sort([handler]):

// Default is ascending:
[2, 3, 1].sort(); // [1, 2, 3]

// But can be descending if you provide a sort handler:
[2, 3, 1].sort(function(a, b) {
    // a = current item in array
    // b = next item in array
    return b - a;
});

實現此目的的一種方法是使用一個變量,該變量在每次調用時都不斷更改其值

let toggler = true;

然后在您的 sortAsc function 中,根據此切換器分配值“asc”或“desc”

sortAsc(customers){
      // Click and sort registered customers by ascending
     toggler = !toggler ;  //change the value based on the current value 
     let order = !toggler ? "asc": "desc";
     let sort = _.orderBy(this.customers, 'registered', order)
     this.sortedCustomers = sort
}

我希望這有幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM