I am trying to filter products in assending and descending order based on product price in vue js using vuex. But not sure how to do

Viewed 95

I have been following youtube tutorials for learning Vue js. so I want to add functionality to this project for filtering the products based upon price.

here is my code

store/index.js

import { createStore } from 'vuex'

function updateLocalStorage(cart) {
    localStorage.setItem('cart', JSON.stringify(cart))
}

export default createStore({
    state: {
        cart: [],
    },
    getters: {
        productQuantity: state => product => {
            const item = state.cart.find(i => i.id === product.id)
            if (item) {
                return item.quantity;
            } else {
                return null;
            }
        },
        cartItems: state => {
            return state.cart
        },
        cartToatal: state => {
            return state.cart.reduce((a, b) => a + (b.val * b.quantity), 0)
        }
    },
    mutations: {
        addItemInCart(state, product) {
            let item = state.cart.find(i => i.id === product.id)

            if (item) {
                item.quantity++;
            } else {
                state.cart.push({...product, quantity: 1 });
            }

            updateLocalStorage(state.cart);
        },
        removeItemFromCart(state, product) {
            let item = state.cart.find(i => i.id === product.id)
            if (item) {
                if (item.quantity > 1) {
                    item.quantity--
                } else {
                    state.cart = state.cart.filter(i => i.id != product.id)
                }
            }

            updateLocalStorage(state.cart);
        },
        updateCartFromLocalStorage(state) {
            const cart = localStorage.getItem('cart')
            if (cart) {
                state.cart = JSON.parse(cart)
            }
        }
    },
    actions: {},
    modules: {}
})

here is what my look like in file data/items.js

const items = [{
        id: 1,
        name: "One Tribe Black Edition",
        img: "https://enftymart.themenio.com/img/nft-lg.8f26d1a6.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 2,
        name: "One Tribe Black New",
        img: "https://miro.medium.com/max/2000/1*AJrLFnuCAD8dE1p1Bg0dbg.jpeg",
        val: "15.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 3,
        name: "One Tribe Black Edition",
        img: "https://creativereview.imgix.net/content/uploads/2021/09/F4E079D612B9653BEFC4D8D2F39781E39A3025C693B177A61D6C73A5156248EA.jpg?auto=compress,format&q=60&w=1200&h=849",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 4,
        name: "One Tribe Black Edition",
        img: "https://coffeebros.com/wp-content/uploads/2021/10/astronaut-background.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 5,
        name: "One Tribe Black Edition",
        img: "https://cloudfront-us-east-1.images.arcpublishing.com/coindesk/5NOWWNNEBRER7BXFZKCYRCA7NA.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 6,
        name: "One Tribe Black Edition",
        img: "https://static01.nyt.com/images/2021/08/15/fashion/TEEN-NFTS--fewocious/TEEN-NFTS--fewocious-videoSixteenByNineJumbo1600.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 7,
        name: "One Tribe Black Edition",
        img: "https://miro.medium.com/max/980/1*3iesg_sr8kC6NYN2iiFHRQ.png",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 8,
        name: "One Tribe Black Edition",
        img: "https://static01.nyt.com/images/2021/08/15/fashion/TEEN-NFTS--fewocious/TEEN-NFTS--fewocious-videoSixteenByNineJumbo1600.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 9,
        name: "One Tribe Black Edition",
        img: "https://www.digitalmusicnews.com/wp-content/uploads/2021/11/are-nfts-a-scam-feat.png",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 10,
        name: "One Tribe Black Edition",
        img: "https://miro.medium.com/max/1082/1*ZZdfsIVNuvbWB15csehQTg.jpeg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 11,
        name: "One Tribe Black Edition",
        img: "https://www.hollywoodreporter.com/wp-content/uploads/2021/10/Mutant-Demon-Ape-Credit-0xb1-copy-H-2021.jpg?w=681&h=383&crop=1",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 12,
        name: "One Tribe Black Edition",
        img: "https://wp-assets.futurism.com/2021/11/person-furious-right-click-saved-precious-nft.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
]

export default items

here is the Vue page where I am trying to filter products I have created to buttons and to methods for descending and ascending order.

<template>
  <div class="home">
    <span class="big-text">NFT</span>
    <div class="nx-container">
      <h1 class="py-45">Get NFT</h1>
      <button class="sort-as" @click="sortUp()">sort up</button>
      <button class="sort-as" @click="sortDown()">sort down</button>
      <div class="flex-it pad-130">
        <product-details
          :product="product"
          :active="active.product_detail"
          v-on:closeDetails="closeDetails()"
        ></product-details>
        <product-summary-container
          v-for="product in items"
          :key="product.id"
          :product="product"
          v-on:explore="viewProduct($event)"
        ></product-summary-container>
      </div>
    </div>
  </div>
</template>

<script>
import ProductSummaryContainer from "../components/products/ProductSummaryContainer.vue";
import ProductDetails from "../components/products/ProductDetails.vue";

import items from "../data/items";

export default {
  name: "Home",
  components: { ProductSummaryContainer, ProductDetails },
  data() {
    return {
      items: items,
      product: null,
      active: {
        product_detail: false,
      },
    };
  },
  methods: {
    viewProduct(product) {
      this.product = product;
      this.active.product_detail = true;
      console.log(product);
    },
    closeDetails() {
      this.active.product_detail = false;
    },
    sortUp($store) { //what i tried
      console.log(this.$store.items.val.sort((a, b) => a - b));
      return $store.items.val.sort((a, b) => a - b);
    },
    sortDown() {},//what i tried
  },
};
</script>

<style>
* {
  margin: 0;
  padding: 0;
  text-align: initial;
}
.nx-container {
  max-width: 1200px;
  overflow-x: hidden;
  overflow-y: auto;
  margin: 0 auto;
}
.flex-it {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}
.pad-130 {
  padding: 0px 15px 130px;
}
.big-text {
  font-family: "Poppins";
  font-size: 16em;
  text-transform: uppercase;
  font-weight: 800;
  position: absolute;
  top: 0;
  right: 0;
  z-index: -6;
  -webkit-text-fill-color: transparent;
  -webkit-text-stroke-width: 0.3px;
}
#app {
  position: relative;
}
</style>

what changes need to be done? Thank you in advance.

3 Answers

There is a lot of missing pieces to your code like how you're iterating over the list of items in the DOM so I can't give a full answer but I think you're simply referencing this.items wrong when you're attempting to sort the list of items in sortUp. you may want your code to be something similar to the following:

    sortUp() { 
      return items.sort((a, b) => parseFloat(a.val) - parseFloat(b.val));
    },

Thanks to @Adam M. I got the idea and I just need to return that sorted item in an array so here is the solution:

sortUp() {
      return this.items.sort((a, b) => parseFloat(a.val) - parseFloat(b.val));
    },
    sortDown() {
      return this.items.sort((a, b) => parseFloat(b.val) - parseFloat(a.val));
    }

What you need to update the list of items on the screes is to use following:

  1. Implement a watcher on the sort data property which is binded to the sorting buttons, it will hold 'asc' 'desc'.

  2. Implement a computed property e.g. filteredItems, in which you'll have a default items List being returned, and if sort value changes then execute your filter logic and return that. And your product-summary-container will use the filteredItems .

Basically, a 'watcher' will detect a change in your sort term. And any 'computed' property, filteredItems in your case, will be fired when watched property changes.

Related