首页  >  问答  >  正文

如何在VueJS中创建排序功能?

我正在尝试在我的 VueJS 代码中创建排序函数。它具有以下字段: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
}

正如你所看到的,我试图通过这个函数对其进行排序,但它不起作用:

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

顺便说一句,productsList:[]是对象列表,因此,我需要按price字段对其进行排序,然后在页面上显示排序后的产品。

谢谢!

P粉438918323P粉438918323240 天前290

全部回复(1)我来回复

  • P粉738248522

    P粉7382485222024-02-22 10:36:07

    您可以通过传递比较器函数来自定义排序算法

    演示

    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;
      });
    }

    回复
    0
  • 取消回复