亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

如何在VueJS中建立排序功能?
P粉438918323
P粉438918323 2024-02-21 11:49:53
0
1
464

我正在嘗試在我的 VueJS 程式碼中建立排序函數(shù)。它具有以下字段:Price:從低到高,Price:從高到低。

所以,這是我的 template

<div name="divSortBy">
        <span>
          Sort by:
        </span>
        <select v-model="sort" name="selectSortBy">
          <option
            v-for="item in sortedList"
            :key="item.id"
            name="selectOptionsSortBy"
            :value="item"
            @click="sortBy"
            v-text="item.title"
          ></option>
        </select>
      </div>

這在 data() { return {} }:

#
sortByItems: [
    {
      id: 1,
      title: 'Price: Low to High',
      sort: 1
    },
    {
      id: 2,
      title: 'Price: High to Low',
      sort: 2
    }
  ],
  sort: null
productsList: [],

這是 compulated

computed: {
sortedList() {
  // FILTER HERE
  if (this.sort) {
    if (this.sort.id === '1') {
      console.log(this.sort.title) // console.log for tests
      this.productsList.sort(function(a, b) {
        return a.price - b.price
      })
    } else if (this.sort.id === '2') {
      console.log(this.sort.title)
    }
  }

  return this.sortByItems
}

正如你所看到的,我試圖透過這個(gè)函數(shù)對(duì)其進(jìn)行排序,但它不起作用:

this.productsList.sort(function(a, b) {
        return a.price - b.price
      }

順便說一句,productsList:[]是物件列表,因此,我需要按price欄位對(duì)其進(jìn)行排序,然後在頁(yè)面上顯示排序後的產(chǎn)品。

謝謝!

P粉438918323
P粉438918323

全部回覆(1)
P粉738248522

您可以透過傳遞比較器函數(shù)來自訂排序演算法

示範(fàn)

if (this.sort.id === "1") {
  return [...this.productsList].sort(function (a, b) {
    return a.price - b.price;
  });
} else if (this.sort.id === "2") {
   return [...this.productsList].sort(function (a, b) {
    return b.price - a.price;
  });
}
最新下載
更多>
網(wǎng)站特效
網(wǎng)站源碼
網(wǎng)站素材
前端模板