首页 > 解决方案 > 重新排序计算数组上的索引?

问题描述

我已经在线搜索了文档和问题,但找不到如何修改我的计算数组的索引顺序。关于从哪里开始的任何想法?

我有一组“优惠”对象,我想在典型的升序或降序选择框中按“offer.price.from”排序。

  <!-- SORT BY SELECT --> 
 <select v-model="sortby" >
 <option value="ascending"> Sort: Price ascending</option>
 <option value="descending"> Sort: Price descending</option>
 </select>

<div v-for="offer in filteredOffers" class="grid-4 item hotel hotel-item"> 
<!-- OFFER CONTENT HERE --> 
</div>

computed: {
filteredOffers () {
return this.offers.filter(offer => {
    return (offer.island === this.filters.islandFilter || this.filters.islandFilter === 'All') // Island 
      && (offer.starrating === this.filters.starRating || this.filters.starRating === 'All') // Star Rating 
      && (offer.board === this.filters.boardBasis || this.filters.boardBasis === 'All') // Board Basis
      && (offer.duration === this.filters.duration || this.filters.duration === 'All') // Duration 
      && (offer.price.from < this.filters.price) // Price
      && (this.filters.travelby === 'sea' && offer.travel.air === false || this.filters.travelby === 'All') // Sea or Air
   // && (this.filters.range.startDate >= offer.dates.start && offer.dates.end <= this.filters.range.endDate)
   });
  }
  }

标签: javascriptvue.jsvuejs2vue-component

解决方案


通过对过滤后的数组进行排序并根据sortby数据项将其作为计算属性返回来尝试此操作:

computed: {
  filteredOffers() {
    let filtered = this.offers.filter(offer => {
      return (offer.island === this.filters.islandFilter || this.filters.islandFilter === 'All') // Island 
        &&
        (offer.starrating === this.filters.starRating || this.filters.starRating === 'All') // Star Rating 
        &&
        (offer.board === this.filters.boardBasis || this.filters.boardBasis === 'All') // Board Basis
        &&
        (offer.duration === this.filters.duration || this.filters.duration === 'All') // Duration 
        &&
        (offer.price.from < this.filters.price) // Price
        &&
        (this.filters.travelby === 'sea' && offer.travel.air === false || this.filters.travelby === 'All') // Sea or Air
      // && (this.filters.range.startDate >= offer.dates.start && offer.dates.end <= this.filters.range.endDate)
    });

    if (this.sortby == 'ascending') {
      return filtered.sort((a, b) => {
        return a.price.form - b.price.form;
      })
    } else {
      return filtered.sort((a, b) => {
        return b.price.form - a.price.form;
      })
    }
  }
}

推荐阅读