Wie erstelle ich eine Sortierfunktion in VueJS?
P粉438918323
P粉438918323 2024-02-21 11:49:53
0
1
292

Ich versuche, eine Sortierfunktion in meinem VueJS-Code zu erstellen. Es hat die folgenden Felder: Price:从低到高Price:从高到低.

Das ist also meins 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>

Das ist data() { return {} }:

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

Das ist 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
}

Wie Sie sehen, versuche ich es nach dieser Funktion zu sortieren, aber es funktioniert nicht:

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

Übrigens, productsList:[]是对象列表,因此,我需要按pricefield sortiert es und zeigt dann die sortierten Produkte auf der Seite an.

Danke!

P粉438918323
P粉438918323

Antworte allen(1)
P粉738248522

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

演示

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;
  });
}
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!