Rumah  >  Soal Jawab  >  teks badan

Bagaimana untuk mencipta fungsi pengisihan dalam VueJS?

Saya cuba mencipta fungsi isihan dalam kod VueJS saya. Ia mempunyai medan berikut: Price:从低到高Price:从高到低.

Jadi, ini milik saya 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>

Ini ialah data() { return {} }:

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

Ini ialah 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
}

Seperti yang anda lihat, saya cuba menyusunnya mengikut fungsi ini, tetapi ia tidak berfungsi:

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

By the way, productsList:[]是对象列表,因此,我需要按pricefield mengisihnya dan kemudian memaparkan produk yang diisih pada halaman.

Terima kasih!

P粉438918323P粉438918323240 hari yang lalu289

membalas semua(1)saya akan balas

  • P粉738248522

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

    Anda boleh menyesuaikan algoritma pengisihan dengan menghantar fungsi pembanding

    Demo

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

    balas
    0
  • Batalbalas