简体   繁体   中英

Sort product according to the price(mrp of products) in vuejs

** Sample Data
storeProducts = [
{ Pname: 'soap', mrp: 50 },
{ Pname: 'facewash', mrp: 30 },
{ Pname: 'shampoo', mrp: 100 }
];

** I'm trying to sort the product based on storeProducts price, I have tried something can anyone let me know how to do that?

  <div class="mt-4">
            <div class="column" v-if="storeProducts.length !== 0">
              <div class="control is-pulled-right">
                <div class="select">
                 <select v-model="sortBy" v-on:change="filteredProduct">
                    <option value="1">Low to High(Price)</option>
                    <option value="2">High to Low(Price)</option>
                  </select>
                </div>
              </div>
            </div>
          </section>
      </div>
</template>

<script>
export default {
  name: 'ProductBySubCategory',
  components: {
    ProductTile,
  },
  data() {
    return {
      products: [],
      storeProducts: [],
      sortBy: 1,
    };
  },
  methods: {
    getRenamedProducts(products) {
      return products.map((prod) => {
        return {
          id: prod.id,
          title: prod.title,
          mrp: prod.mrp,
          realUnit: prod.unit,
        };
      });
    },
  },
  computed: {
     filteredProduct: function () {
      return this.storeProducts.sort((a, b) => {
      if (this.sortBy == '1') {
     return b.mrp - a.mrp;
        } else if (this.sortyBy == '2') {
         return a.mrp - b.mrp;
         }
    });
     },
  },
};
</script>```



Try this:

filteredProduct: function() {
  const sortBy = this.sortBy;
  return this.storeProducts.sort((a, b) => {
    if (sortBy === '1') {
      return b.mrp - a.mrp;
    } else if (sortBy === '2') {
      return a.mrp - b.mrp;
    }
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM